mirror of
https://github.com/SigNoz/signoz.git
synced 2026-11-03 23:10:59 +00:00
Compare commits
2 Commits
ci/e2e-nod
...
tvats-aggr
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
25ac727789 | ||
|
|
ff637baae5 |
8
.github/workflows/e2eci.yaml
vendored
8
.github/workflows/e2eci.yaml
vendored
@@ -47,7 +47,7 @@ jobs:
|
||||
- name: node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "22"
|
||||
node-version: lts/*
|
||||
- name: install-pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
with:
|
||||
@@ -67,7 +67,7 @@ jobs:
|
||||
matrix:
|
||||
project:
|
||||
- chromium
|
||||
shard: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
||||
shard: [1, 2, 3, 4]
|
||||
needs: changes
|
||||
if: needs.changes.outputs.e2e == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
@@ -105,7 +105,7 @@ jobs:
|
||||
- name: node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "22"
|
||||
node-version: lts/*
|
||||
- name: install-pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
with:
|
||||
@@ -162,7 +162,7 @@ jobs:
|
||||
- name: playwright-test
|
||||
run: |
|
||||
cd tests/e2e && \
|
||||
pnpm playwright test --project=${{ matrix.project }} --shard=${{ matrix.shard }}/10
|
||||
pnpm playwright test --project=${{ matrix.project }} --shard=${{ matrix.shard }}/4
|
||||
- name: teardown-stack
|
||||
if: always()
|
||||
run: |
|
||||
|
||||
@@ -2205,10 +2205,10 @@ components:
|
||||
type: object
|
||||
CloudintegrationtypesAWSConnectionArtifact:
|
||||
properties:
|
||||
cliCommand:
|
||||
connectionUrl:
|
||||
type: string
|
||||
required:
|
||||
- cliCommand
|
||||
- connectionUrl
|
||||
type: object
|
||||
CloudintegrationtypesAWSIntegrationConfig:
|
||||
properties:
|
||||
@@ -2364,8 +2364,11 @@ components:
|
||||
properties:
|
||||
cliCommand:
|
||||
type: string
|
||||
cloudPowerShellCommand:
|
||||
type: string
|
||||
required:
|
||||
- cliCommand
|
||||
- cloudPowerShellCommand
|
||||
type: object
|
||||
CloudintegrationtypesAzureIntegrationConfig:
|
||||
properties:
|
||||
|
||||
@@ -28,7 +28,7 @@ func ConvertConfig(src ExternalConfig) (InternalConfig, error)
|
||||
// Over this:
|
||||
type ConfigAdapter struct { ... }
|
||||
func NewConfigAdapter(src ExternalConfig) *ConfigAdapter
|
||||
func (adapter *ConfigAdapter) ToInternal() (InternalConfig, error)
|
||||
func (a *ConfigAdapter) ToInternal() (InternalConfig, error)
|
||||
```
|
||||
|
||||
The two-step version is only justified when `ConfigAdapter` has multiple distinct consumers that use it in different ways.
|
||||
@@ -66,10 +66,10 @@ A method on a structured type should not strip meaning from the structure it bel
|
||||
|
||||
```go
|
||||
// Problematic: callers cannot distinguish how items were related.
|
||||
func (order *Order) AllLineItems() []LineItem { ... }
|
||||
func (o *Order) AllLineItems() []LineItem { ... }
|
||||
|
||||
// Better: the validation logic operates on the full structure.
|
||||
func ValidateOrder(order *Order) error { ... }
|
||||
func ValidateOrder(o *Order) error { ... }
|
||||
```
|
||||
|
||||
Public methods shape how a type is used. Once a lossy accessor exists, callers will depend on it, and the lost information becomes unrecoverable at those call sites.
|
||||
|
||||
@@ -74,7 +74,7 @@ The `*Visitor` passed in provides everything needed to build predicates. Use the
|
||||
In the simplest case, keys map straight to columns and the resolver is a switch. The doc's running example, an imaginary `sample_entity` table:
|
||||
|
||||
```go
|
||||
func (resolver sampleEntityFieldResolver) ResolveComparison(v *sqlcompiler.Visitor, key string, operation qbtypesv5.FilterOperator, ctx *grammar.ComparisonContext) string {
|
||||
func (r sampleEntityFieldResolver) ResolveComparison(v *sqlcompiler.Visitor, key string, operation qbtypesv5.FilterOperator, ctx *grammar.ComparisonContext) string {
|
||||
switch key {
|
||||
case "created_by":
|
||||
return v.BuildStringOperation(v.Sb, ctx, operation, "sample_entity.created_by", key)
|
||||
|
||||
@@ -82,7 +82,7 @@ In the module implementation, implement the new method. A typical implementation
|
||||
- Uses the `render` package to write responses or errors
|
||||
|
||||
```go
|
||||
func (handler *handler) CreateThing(rw http.ResponseWriter, req *http.Request) {
|
||||
func (h *handler) CreateThing(rw http.ResponseWriter, req *http.Request) {
|
||||
// Extract authentication and organization context from req.Context()
|
||||
claims, err := authtypes.ClaimsFromContext(req.Context())
|
||||
if err != nil {
|
||||
@@ -98,7 +98,7 @@ func (handler *handler) CreateThing(rw http.ResponseWriter, req *http.Request) {
|
||||
}
|
||||
|
||||
// Call module functions
|
||||
out, err := handler.module.CreateThing(req.Context(), claims.OrgID, &in)
|
||||
out, err := h.module.CreateThing(req.Context(), claims.OrgID, &in)
|
||||
if err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
|
||||
@@ -59,8 +59,7 @@ Follow these rules:
|
||||
|
||||
### Unexported symbols
|
||||
|
||||
- Struct receivers: the lowercase name of the role the type plays, the same on every method of the type (`provider`, `module`, `handler`, `store`, `middleware`, `migration`). Never one or two characters: `c`, `h`, `m` say nothing at the call site and collide with local variables.
|
||||
- When the receiver name would shadow an imported package, alias the import, not the receiver (`pkghandler "github.com/SigNoz/signoz/pkg/http/handler"` with a `handler` receiver).
|
||||
- Struct receivers: one or two characters (`c`, `f`, `br`).
|
||||
- Helper functions: descriptive lowercase names (`parseToken`, `buildQuery`).
|
||||
|
||||
### Constants
|
||||
|
||||
@@ -70,16 +70,16 @@ The instrumentation SDK (`pkg/instrumentation/sdk.go`) is idle while running but
|
||||
```go
|
||||
// pkg/instrumentation/sdk.go
|
||||
|
||||
func (sdk *SDK) Start(ctx context.Context) error {
|
||||
<-sdk.startCh
|
||||
func (i *SDK) Start(ctx context.Context) error {
|
||||
<-i.startCh
|
||||
return nil
|
||||
}
|
||||
|
||||
func (sdk *SDK) Stop(ctx context.Context) error {
|
||||
close(sdk.startCh)
|
||||
func (i *SDK) Stop(ctx context.Context) error {
|
||||
close(i.startCh)
|
||||
return errors.Join(
|
||||
sdk.sdk.Shutdown(ctx),
|
||||
sdk.meterProviderShutdownFunc(ctx),
|
||||
i.sdk.Shutdown(ctx),
|
||||
i.meterProviderShutdownFunc(ctx),
|
||||
)
|
||||
}
|
||||
```
|
||||
@@ -197,8 +197,8 @@ A standalone service only has the `factory.Service` lifecycle i.e it does not se
|
||||
}
|
||||
}
|
||||
|
||||
func (service *service) Start(ctx context.Context) error { ... }
|
||||
func (service *service) Stop(ctx context.Context) error { ... }
|
||||
func (s *service) Start(ctx context.Context) error { ... }
|
||||
func (s *service) Stop(ctx context.Context) error { ... }
|
||||
```
|
||||
|
||||
### Provider that is also a service
|
||||
|
||||
@@ -17,7 +17,7 @@ Two rules shape how the core type behaves:
|
||||
func NewGettableAuthDomainFromAuthDomain(d *AuthDomain, info *AuthNProviderInfo) *GettableAuthDomain
|
||||
|
||||
// Receiver form
|
||||
func (maintenance *PlannedMaintenanceWithRules) ToPlannedMaintenance() *PlannedMaintenance
|
||||
func (m *PlannedMaintenanceWithRules) ToPlannedMaintenance() *PlannedMaintenance
|
||||
```
|
||||
- **`X` can double as the storage row** when the DB shape would be identical. `Channel` embeds `bun.BaseModel` directly, and there is no `StorableChannel`. This is the preferred shape when it works.
|
||||
|
||||
@@ -175,10 +175,10 @@ The rules that make the envelope work:
|
||||
|
||||
```go
|
||||
// Domain invariants: every write path re-runs these.
|
||||
func (entity *X) Validate() error { ... }
|
||||
func (x *X) Validate() error { ... }
|
||||
|
||||
// Request-shape-only: checks that do not apply once the value is persisted.
|
||||
func (postable *PostableX) Validate() error { ... }
|
||||
func (p *PostableX) Validate() error { ... }
|
||||
```
|
||||
- **Type aliases, not wrappers**, when two shapes are identical. `type GettableChannels = []*Channel` is correct because it adds no semantics beyond the underlying type.
|
||||
- **Serialization tags** follow [handler.md](handler.md): `required:"true"` means the JSON key must be present, `nullable:"true"` is required on any slice or map that may serialize as `null`, and types with a fixed value set must implement `Enum() []any`.
|
||||
|
||||
@@ -2,6 +2,8 @@ package implcloudprovider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"sort"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/modules/cloudintegration"
|
||||
@@ -16,14 +18,29 @@ func NewAWSCloudProvider(defStore cloudintegrationtypes.ServiceDefinitionStore)
|
||||
return &awscloudprovider{serviceDefinitions: defStore}, nil
|
||||
}
|
||||
|
||||
// TODO: move URL construction logic to cloudintegrationtypes and add unit tests for it.
|
||||
func (provider *awscloudprovider) GetConnectionArtifact(ctx context.Context, account *cloudintegrationtypes.Account, req *cloudintegrationtypes.GetConnectionArtifactRequest) (*cloudintegrationtypes.ConnectionArtifact, error) {
|
||||
connectionArtifact, err := cloudintegrationtypes.NewAWSConnectionArtifact(account.ID, req.Config.AgentVersion, req.Credentials, req.Config.AWS.DeploymentRegion)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
baseURL := fmt.Sprintf(cloudintegrationtypes.CloudFormationQuickCreateBaseURL.StringValue(), req.Config.AWS.DeploymentRegion)
|
||||
u, _ := url.Parse(baseURL)
|
||||
|
||||
q := u.Query()
|
||||
q.Set("region", req.Config.AWS.DeploymentRegion)
|
||||
u.Fragment = "/stacks/quickcreate"
|
||||
|
||||
u.RawQuery = q.Encode()
|
||||
|
||||
q = u.Query()
|
||||
q.Set("stackName", cloudintegrationtypes.AgentCloudFormationBaseStackName.StringValue())
|
||||
q.Set("templateURL", fmt.Sprintf(cloudintegrationtypes.AgentCloudFormationTemplateS3Path.StringValue(), req.Config.AgentVersion))
|
||||
q.Set("param_SigNozIntegrationAgentVersion", req.Config.AgentVersion)
|
||||
q.Set("param_SigNozApiUrl", req.Credentials.SigNozAPIURL)
|
||||
q.Set("param_SigNozApiKey", req.Credentials.SigNozAPIKey)
|
||||
q.Set("param_SigNozAccountId", account.ID.StringValue())
|
||||
q.Set("param_IngestionUrl", req.Credentials.IngestionURL)
|
||||
q.Set("param_IngestionKey", req.Credentials.IngestionKey)
|
||||
|
||||
return &cloudintegrationtypes.ConnectionArtifact{
|
||||
AWS: connectionArtifact,
|
||||
AWS: cloudintegrationtypes.NewAWSConnectionArtifact(u.String() + "?&" + q.Encode()), // this format is required by AWS
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -3936,7 +3936,7 @@ export interface CloudintegrationtypesAWSConnectionArtifactDTO {
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
cliCommand: string;
|
||||
connectionUrl: string;
|
||||
}
|
||||
|
||||
export interface CloudintegrationtypesAWSLogsCollectionStrategyDTO {
|
||||
@@ -4146,6 +4146,10 @@ export interface CloudintegrationtypesAzureConnectionArtifactDTO {
|
||||
* @type string
|
||||
*/
|
||||
cliCommand: string;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
cloudPowerShellCommand: string;
|
||||
}
|
||||
|
||||
export interface CloudintegrationtypesAzureLogsCollectionStrategyDTO {
|
||||
|
||||
@@ -25,8 +25,6 @@ import {
|
||||
import '@testing-library/jest-dom';
|
||||
|
||||
import { QueryBuilderV2 } from '../../QueryBuilderV2';
|
||||
import { QueryBuilderV2Provider } from '../../QueryBuilderV2Context';
|
||||
import { QueryV2 } from '../QueryV2';
|
||||
|
||||
// Local mocks for domain-specific heavy child components
|
||||
jest.mock(
|
||||
@@ -251,7 +249,11 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
|
||||
|
||||
describe('query actions menu', () => {
|
||||
const openQueryActions = async (): Promise<void> => {
|
||||
await userEvent.click(screen.getAllByTestId('query-actions')[0]);
|
||||
const trigger = document.querySelector(
|
||||
'.query-actions-container [aria-haspopup="menu"]',
|
||||
) as HTMLElement;
|
||||
expect(trigger).toBeInTheDocument();
|
||||
await userEvent.click(trigger);
|
||||
};
|
||||
|
||||
it('Clone calls cloneQuery with the query', async () => {
|
||||
@@ -259,7 +261,7 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
|
||||
|
||||
await openQueryActions();
|
||||
await userEvent.click(
|
||||
await screen.findByTestId('query-actions-item-clone-query'),
|
||||
await screen.findByRole('menuitem', { name: 'Clone' }),
|
||||
);
|
||||
|
||||
expect(baseQBContext.cloneQuery).toHaveBeenCalledTimes(1);
|
||||
@@ -273,44 +275,41 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
|
||||
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
|
||||
|
||||
await openQueryActions();
|
||||
await screen.findByTestId('query-actions-item-clone-query');
|
||||
await screen.findByRole('menuitem', { name: 'Clone' });
|
||||
|
||||
expect(
|
||||
screen.queryByTestId('query-actions-item-delete-query'),
|
||||
screen.queryByRole('menuitem', { name: 'Delete' }),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows Delete with more than one query and deletes on click', async () => {
|
||||
const [queryA] = (baseQBContext.currentQuery as Query).builder.queryData;
|
||||
const currentQueryBase = baseQBContext.currentQuery as Query;
|
||||
const [queryA] = currentQueryBase.builder.queryData;
|
||||
mockedUseQueryBuilder.mockReturnValue({
|
||||
...baseQBContext,
|
||||
currentQuery: {
|
||||
...currentQueryBase,
|
||||
builder: {
|
||||
...currentQueryBase.builder,
|
||||
queryData: [queryA, { ...queryA, queryName: 'B', legend: 'B' }],
|
||||
},
|
||||
},
|
||||
});
|
||||
const handleDeleteQuery = jest.fn();
|
||||
mockedUseQueryOperations.mockReturnValue({
|
||||
...mockedUseQueryOperations({} as Parameters<UseQueryOperations>[0]),
|
||||
handleDeleteQuery,
|
||||
});
|
||||
|
||||
render(
|
||||
<QueryBuilderV2Provider>
|
||||
<QueryV2
|
||||
index={0}
|
||||
query={queryA}
|
||||
version="v4"
|
||||
isAvailableToDisable={false}
|
||||
isMultiQueryAllowed
|
||||
queriesCount={2}
|
||||
onSignalSourceChange={jest.fn()}
|
||||
signalSourceChangeEnabled={false}
|
||||
savePreviousQuery={false}
|
||||
/>
|
||||
</QueryBuilderV2Provider>,
|
||||
);
|
||||
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
|
||||
|
||||
await openQueryActions();
|
||||
await userEvent.click(
|
||||
await screen.findByTestId('query-actions-item-delete-query'),
|
||||
await screen.findByRole('menuitem', { name: 'Delete' }),
|
||||
);
|
||||
|
||||
expect(handleDeleteQuery).toHaveBeenCalledTimes(1);
|
||||
}, 15000);
|
||||
});
|
||||
});
|
||||
|
||||
it('fx button is disabled when functions already exist', () => {
|
||||
|
||||
@@ -15,7 +15,14 @@ function AlertMessage({
|
||||
<Callout
|
||||
title={
|
||||
<div className="cloud-account-setup-form__alert-message">
|
||||
<Spin indicator={<LoaderCircle size={14} className="animate-spin" />} />
|
||||
<Spin
|
||||
indicator={
|
||||
<LoaderCircle
|
||||
size={14}
|
||||
className="anticon anticon-loading anticon-spin ant-spin-dot"
|
||||
/>
|
||||
}
|
||||
/>
|
||||
Waiting for connection, retrying in{' '}
|
||||
<span className="retry-time">10</span> secs...
|
||||
</div>
|
||||
|
||||
@@ -12,13 +12,6 @@
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
&__footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
&__content {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
@@ -151,6 +144,52 @@
|
||||
}
|
||||
}
|
||||
|
||||
.cloud-account-setup-form__code-block-tabs {
|
||||
padding: 8px;
|
||||
border-radius: 4px;
|
||||
border: 1px solid var(--l2-border);
|
||||
background: var(--l2-background);
|
||||
|
||||
&-header {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
|
||||
margin-bottom: 12px;
|
||||
|
||||
&-title {
|
||||
color: var(--l1-foreground);
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
line-height: 20px;
|
||||
letter-spacing: -0.07px;
|
||||
}
|
||||
|
||||
&-description {
|
||||
color: var(--l2-foreground);
|
||||
font-size: 12px;
|
||||
font-weight: 400;
|
||||
line-height: 18px;
|
||||
letter-spacing: -0.06px;
|
||||
}
|
||||
}
|
||||
|
||||
[role='tablist'] {
|
||||
gap: 8px !important;
|
||||
}
|
||||
|
||||
[role='tabpanel'] {
|
||||
padding: 0 !important;
|
||||
}
|
||||
|
||||
[data-slot='tabs-item'] {
|
||||
padding: 4px 24px !important;
|
||||
border: none !important;
|
||||
background-color: transparent !important;
|
||||
font-size: 12px !important;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes cloud-account-setup-accordion-reveal {
|
||||
from {
|
||||
opacity: 0;
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import { useCallback } from 'react';
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { DrawerWrapper } from '@signozhq/ui/drawer';
|
||||
import { useIntegrationModal } from 'hooks/integration/aws/useIntegrationModal';
|
||||
import { SquareArrowOutUpRight } from '@signozhq/icons';
|
||||
|
||||
import {
|
||||
ActiveViewEnum,
|
||||
IntegrationModalProps,
|
||||
ModalStateEnum,
|
||||
} from '../../../HeroSection/types';
|
||||
import CloseSetupConfirm from '../../CloseSetupConfirm/CloseSetupConfirm';
|
||||
import { useCloseSetupConfirm } from '../../CloseSetupConfirm/useCloseSetupConfirm';
|
||||
import { RegionForm } from '../RegionForm/RegionForm';
|
||||
|
||||
import './CloudAccountSetupModal.style.scss';
|
||||
@@ -24,24 +24,22 @@ function CloudAccountSetupModal({
|
||||
activeView,
|
||||
selectedRegions,
|
||||
includeAllRegions,
|
||||
isGeneratingCommand,
|
||||
connectionCommand,
|
||||
isGeneratingUrl,
|
||||
setSelectedRegions,
|
||||
setIncludeAllRegions,
|
||||
handleRegionSelect,
|
||||
handleSubmit,
|
||||
handleClose,
|
||||
setActiveView,
|
||||
accountId,
|
||||
handleRegionChange,
|
||||
connectionParams,
|
||||
isConnectionParamsLoading,
|
||||
checkConnectionAgain,
|
||||
handleConnectionSuccess,
|
||||
handleConnectionTimeout,
|
||||
handleConnectionError,
|
||||
} = useIntegrationModal({ onClose });
|
||||
|
||||
const { isConfirmOpen, setIsConfirmOpen, requestClose } = useCloseSetupConfirm(
|
||||
{ shouldConfirm: Boolean(connectionCommand), onClose: handleClose },
|
||||
);
|
||||
|
||||
const renderContent = useCallback(() => {
|
||||
return (
|
||||
<div className="cloud-account-setup-modal__content">
|
||||
@@ -52,12 +50,15 @@ function CloudAccountSetupModal({
|
||||
includeAllRegions={includeAllRegions}
|
||||
onRegionSelect={handleRegionSelect}
|
||||
onSubmit={handleSubmit}
|
||||
connectionCommand={connectionCommand}
|
||||
accountId={accountId}
|
||||
handleRegionChange={handleRegionChange}
|
||||
connectionParams={connectionParams}
|
||||
isConnectionParamsLoading={isConnectionParamsLoading}
|
||||
setSelectedRegions={setSelectedRegions}
|
||||
setIncludeAllRegions={setIncludeAllRegions}
|
||||
onConnectionSuccess={handleConnectionSuccess}
|
||||
onConnectionTimeout={handleConnectionTimeout}
|
||||
onConnectionError={handleConnectionError}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
@@ -68,50 +69,38 @@ function CloudAccountSetupModal({
|
||||
includeAllRegions,
|
||||
handleRegionSelect,
|
||||
handleSubmit,
|
||||
connectionCommand,
|
||||
accountId,
|
||||
handleRegionChange,
|
||||
connectionParams,
|
||||
isConnectionParamsLoading,
|
||||
setSelectedRegions,
|
||||
setIncludeAllRegions,
|
||||
handleConnectionSuccess,
|
||||
handleConnectionTimeout,
|
||||
handleConnectionError,
|
||||
]);
|
||||
|
||||
const footer = (
|
||||
<div className="cloud-account-setup-modal__footer">
|
||||
<Button
|
||||
disabledTooltip={
|
||||
selectedRegions.length === 0
|
||||
? 'Select at least one region'
|
||||
: 'Waiting for the account to connect'
|
||||
}
|
||||
size="md"
|
||||
variant="outlined"
|
||||
color="secondary"
|
||||
onClick={requestClose}
|
||||
testId="aws-cancel-btn"
|
||||
variant="solid"
|
||||
color="primary"
|
||||
prefix={<SquareArrowOutUpRight size={17} color={Color.BG_VANILLA_100} />}
|
||||
onClick={handleSubmit}
|
||||
testId="aws-launch-cfn-btn"
|
||||
disabled={
|
||||
selectedRegions.length === 0 || modalState === ModalStateEnum.WAITING
|
||||
}
|
||||
loading={isLoading || isGeneratingUrl}
|
||||
>
|
||||
Cancel
|
||||
Launch Cloud Formation Template
|
||||
</Button>
|
||||
{!connectionCommand && (
|
||||
<Button
|
||||
disabledTooltip="Select at least one region"
|
||||
size="md"
|
||||
variant="solid"
|
||||
color="primary"
|
||||
onClick={handleSubmit}
|
||||
disabled={selectedRegions.length === 0}
|
||||
loading={isLoading || isGeneratingCommand}
|
||||
testId="aws-generate-command-btn"
|
||||
>
|
||||
Generate Command
|
||||
</Button>
|
||||
)}
|
||||
{modalState === ModalStateEnum.ERROR && connectionCommand && (
|
||||
<Button
|
||||
size="md"
|
||||
variant="solid"
|
||||
color="primary"
|
||||
onClick={checkConnectionAgain}
|
||||
testId="aws-check-connection-btn"
|
||||
>
|
||||
Check Again
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -124,17 +113,22 @@ function CloudAccountSetupModal({
|
||||
const viewConfigs = {
|
||||
[ActiveViewEnum.FORM]: {
|
||||
title: 'Add AWS Account',
|
||||
okText: 'Generate Command',
|
||||
okText: (
|
||||
<div className="cloud-account-setup-form__submit-button-content">
|
||||
Launch Cloud Formation Template{' '}
|
||||
<SquareArrowOutUpRight size={17} color={Color.BG_VANILLA_100} />
|
||||
</div>
|
||||
),
|
||||
onOk: handleSubmit,
|
||||
disabled:
|
||||
isLoading || isGeneratingCommand || modalState === ModalStateEnum.WAITING,
|
||||
isLoading || isGeneratingUrl || modalState === ModalStateEnum.WAITING,
|
||||
cancelButtonProps: { style: { display: 'none' } },
|
||||
},
|
||||
[ActiveViewEnum.SELECT_REGIONS]: {
|
||||
title: 'Which regions do you want to monitor?',
|
||||
okText: `Confirm Selection (${getSelectedRegionsCount()})`,
|
||||
onOk: (): void => setActiveView(ActiveViewEnum.FORM),
|
||||
isLoading: isLoading || isGeneratingCommand,
|
||||
isLoading: isLoading || isGeneratingUrl,
|
||||
cancelButtonProps: { style: { display: 'block' } },
|
||||
disabled: false,
|
||||
},
|
||||
@@ -146,7 +140,7 @@ function CloudAccountSetupModal({
|
||||
handleSubmit,
|
||||
getSelectedRegionsCount,
|
||||
isLoading,
|
||||
isGeneratingCommand,
|
||||
isGeneratingUrl,
|
||||
activeView,
|
||||
setActiveView,
|
||||
]);
|
||||
@@ -155,32 +149,23 @@ function CloudAccountSetupModal({
|
||||
|
||||
const handleDrawerOpenChange = (open: boolean): void => {
|
||||
if (!open) {
|
||||
requestClose();
|
||||
handleClose();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<DrawerWrapper
|
||||
open={true}
|
||||
className="cloud-account-setup-modal"
|
||||
onOpenChange={handleDrawerOpenChange}
|
||||
direction="right"
|
||||
showCloseButton
|
||||
title={modalConfig.title}
|
||||
width="wide"
|
||||
footer={footer}
|
||||
>
|
||||
{renderContent()}
|
||||
</DrawerWrapper>
|
||||
<CloseSetupConfirm
|
||||
providerName="AWS"
|
||||
testIdPrefix="aws"
|
||||
open={isConfirmOpen}
|
||||
onOpenChange={setIsConfirmOpen}
|
||||
onConfirm={handleClose}
|
||||
/>
|
||||
</>
|
||||
<DrawerWrapper
|
||||
open={true}
|
||||
className="cloud-account-setup-modal"
|
||||
onOpenChange={handleDrawerOpenChange}
|
||||
direction="right"
|
||||
showCloseButton
|
||||
title={modalConfig.title}
|
||||
width="wide"
|
||||
footer={footer}
|
||||
>
|
||||
{renderContent()}
|
||||
</DrawerWrapper>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -11,9 +11,11 @@ import { RegionSelector } from './RegionForm/RegionSelector';
|
||||
function RegionDeploymentSection({
|
||||
regions,
|
||||
handleRegionChange,
|
||||
isFormDisabled,
|
||||
}: {
|
||||
regions: Region[];
|
||||
handleRegionChange: (value: string) => void;
|
||||
isFormDisabled: boolean;
|
||||
}): JSX.Element {
|
||||
return (
|
||||
<div className="cloud-account-setup-form__form-group">
|
||||
@@ -34,6 +36,7 @@ function RegionDeploymentSection({
|
||||
suffixIcon={<ChevronDown size={16} color={Color.BG_VANILLA_400} />}
|
||||
className="cloud-account-setup-form__select integrations-select"
|
||||
onChange={handleRegionChange}
|
||||
disabled={isFormDisabled}
|
||||
getPopupContainer={popupContainer}
|
||||
>
|
||||
{regions.flatMap((region) =>
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
import { useRef } from 'react';
|
||||
import { Form } from 'antd';
|
||||
import { RegionFormProps } from 'container/Integrations/HeroSection/types';
|
||||
import { useGetAccount } from 'api/generated/services/cloudintegration';
|
||||
import cx from 'classnames';
|
||||
import { INTEGRATION_TYPES } from 'container/Integrations/constants';
|
||||
import {
|
||||
ModalStateEnum,
|
||||
RegionFormProps,
|
||||
} from 'container/Integrations/HeroSection/types';
|
||||
import { regions } from 'utils/regions';
|
||||
|
||||
import AgentSetupCommand from '../../AgentSetupCommand/AgentSetupCommand';
|
||||
import AlertMessage from '../../AlertMessage';
|
||||
import {
|
||||
ComplianceNote,
|
||||
@@ -16,13 +22,56 @@ export function RegionForm({
|
||||
modalState,
|
||||
selectedRegions,
|
||||
onSubmit,
|
||||
connectionCommand,
|
||||
accountId,
|
||||
handleRegionChange,
|
||||
connectionParams,
|
||||
isConnectionParamsLoading,
|
||||
setSelectedRegions,
|
||||
setIncludeAllRegions,
|
||||
onConnectionSuccess,
|
||||
onConnectionTimeout,
|
||||
onConnectionError,
|
||||
}: RegionFormProps): JSX.Element {
|
||||
const startTimeRef = useRef(Date.now());
|
||||
const refetchInterval = 10 * 1000;
|
||||
const errorTimeout = 10 * 60 * 1000;
|
||||
|
||||
const { isLoading: isAccountStatusLoading } = useGetAccount(
|
||||
{
|
||||
cloudProvider: INTEGRATION_TYPES.AWS,
|
||||
id: accountId ?? '',
|
||||
},
|
||||
{
|
||||
query: {
|
||||
refetchInterval,
|
||||
enabled: !!accountId && modalState === ModalStateEnum.WAITING,
|
||||
onSuccess: (response) => {
|
||||
const isConnected =
|
||||
Boolean(response.data.providerAccountId) &&
|
||||
response.data.removedAt === null;
|
||||
|
||||
if (isConnected) {
|
||||
const cloudAccountId =
|
||||
response.data.providerAccountId ?? response.data.id;
|
||||
|
||||
onConnectionSuccess({
|
||||
cloudAccountId,
|
||||
status: response.data.agentReport,
|
||||
});
|
||||
} else if (Date.now() - startTimeRef.current >= errorTimeout) {
|
||||
onConnectionTimeout({ id: accountId });
|
||||
}
|
||||
},
|
||||
onError: () => {
|
||||
onConnectionError();
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const isFormDisabled =
|
||||
modalState === ModalStateEnum.WAITING || isAccountStatusLoading;
|
||||
|
||||
return (
|
||||
<Form
|
||||
form={form}
|
||||
@@ -30,30 +79,28 @@ export function RegionForm({
|
||||
layout="vertical"
|
||||
onFinish={onSubmit}
|
||||
>
|
||||
{connectionCommand ? (
|
||||
<AgentSetupCommand
|
||||
description="Run this command in AWS CloudShell, or in a terminal where the AWS CLI is signed in to the account you want to monitor. It contains your SigNoz keys, so do not share it."
|
||||
command={connectionCommand}
|
||||
testId="aws-agent-command"
|
||||
<div
|
||||
className={cx(`cloud-account-setup-form__content`, {
|
||||
disabled: isFormDisabled,
|
||||
})}
|
||||
>
|
||||
<RegionDeploymentSection
|
||||
regions={regions}
|
||||
handleRegionChange={handleRegionChange}
|
||||
isFormDisabled={isFormDisabled}
|
||||
/>
|
||||
) : (
|
||||
<div className="cloud-account-setup-form__content">
|
||||
<RegionDeploymentSection
|
||||
regions={regions}
|
||||
handleRegionChange={handleRegionChange}
|
||||
/>
|
||||
<MonitoringRegionsSection
|
||||
selectedRegions={selectedRegions}
|
||||
setSelectedRegions={setSelectedRegions}
|
||||
setIncludeAllRegions={setIncludeAllRegions}
|
||||
/>
|
||||
<ComplianceNote />
|
||||
<RenderConnectionFields
|
||||
isConnectionParamsLoading={isConnectionParamsLoading}
|
||||
connectionParams={connectionParams}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<MonitoringRegionsSection
|
||||
selectedRegions={selectedRegions}
|
||||
setSelectedRegions={setSelectedRegions}
|
||||
setIncludeAllRegions={setIncludeAllRegions}
|
||||
/>
|
||||
<ComplianceNote />
|
||||
<RenderConnectionFields
|
||||
isConnectionParamsLoading={isConnectionParamsLoading}
|
||||
connectionParams={connectionParams}
|
||||
isFormDisabled={isFormDisabled}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="cloud-account-setup-form__alert">
|
||||
<AlertMessage modalState={modalState} />
|
||||
|
||||
@@ -5,9 +5,11 @@ import { CloudintegrationtypesCredentialsDTO } from 'api/generated/services/sigN
|
||||
function RenderConnectionFields({
|
||||
isConnectionParamsLoading,
|
||||
connectionParams,
|
||||
isFormDisabled,
|
||||
}: {
|
||||
isConnectionParamsLoading?: boolean;
|
||||
connectionParams?: CloudintegrationtypesCredentialsDTO | null;
|
||||
isFormDisabled?: boolean;
|
||||
}): JSX.Element | null {
|
||||
if (
|
||||
isConnectionParamsLoading ||
|
||||
@@ -27,7 +29,7 @@ function RenderConnectionFields({
|
||||
label="Ingestion URL"
|
||||
rules={[{ required: true, message: 'Please enter ingestion URL' }]}
|
||||
>
|
||||
<Input placeholder="Enter ingestion URL" />
|
||||
<Input placeholder="Enter ingestion URL" disabled={isFormDisabled} />
|
||||
</Form.Item>
|
||||
)}
|
||||
{!connectionParams?.ingestionKey && (
|
||||
@@ -36,7 +38,7 @@ function RenderConnectionFields({
|
||||
label="Ingestion Key"
|
||||
rules={[{ required: true, message: 'Please enter ingestion key' }]}
|
||||
>
|
||||
<Input placeholder="Enter ingestion key" />
|
||||
<Input placeholder="Enter ingestion key" disabled={isFormDisabled} />
|
||||
</Form.Item>
|
||||
)}
|
||||
{!connectionParams?.sigNozApiUrl && (
|
||||
@@ -45,7 +47,7 @@ function RenderConnectionFields({
|
||||
label="SigNoz API URL"
|
||||
rules={[{ required: true, message: 'Please enter SigNoz API URL' }]}
|
||||
>
|
||||
<Input placeholder="Enter SigNoz API URL" />
|
||||
<Input placeholder="Enter SigNoz API URL" disabled={isFormDisabled} />
|
||||
</Form.Item>
|
||||
)}
|
||||
{!connectionParams?.sigNozApiKey && (
|
||||
@@ -54,7 +56,7 @@ function RenderConnectionFields({
|
||||
label="SigNoz API KEY"
|
||||
rules={[{ required: true, message: 'Please enter SigNoz API Key' }]}
|
||||
>
|
||||
<Input placeholder="Enter SigNoz API Key" />
|
||||
<Input placeholder="Enter SigNoz API Key" disabled={isFormDisabled} />
|
||||
</Form.Item>
|
||||
)}
|
||||
</Form.Item>
|
||||
@@ -63,6 +65,7 @@ function RenderConnectionFields({
|
||||
|
||||
RenderConnectionFields.defaultProps = {
|
||||
connectionParams: null,
|
||||
isFormDisabled: false,
|
||||
isConnectionParamsLoading: false,
|
||||
};
|
||||
|
||||
|
||||
@@ -1,168 +0,0 @@
|
||||
import { ComponentProps } from 'react';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { RestRequest } from 'msw';
|
||||
import type logEvent from '../../../../../api/common/logEvent';
|
||||
|
||||
import CloudAccountSetupModal from '../AddNewAccount/CloudAccountSetupModal';
|
||||
|
||||
// `useIntegrationModal` imports logEvent by relative path, which the
|
||||
// jest.config moduleNameMapper (keyed on the `api/common/logEvent` alias) does
|
||||
// not intercept, so mock the resolved module directly.
|
||||
jest.mock('../../../../../api/common/logEvent', () => ({
|
||||
__esModule: true,
|
||||
default: jest.fn() as jest.MockedFunction<typeof logEvent>,
|
||||
}));
|
||||
|
||||
// The form flow drives antd selects and typing, which outruns the 5s default on CI.
|
||||
jest.setTimeout(15_000);
|
||||
|
||||
type OnClose = ComponentProps<typeof CloudAccountSetupModal>['onClose'];
|
||||
|
||||
const mockOnClose = (): jest.MockedFunction<OnClose> =>
|
||||
jest.fn() as jest.MockedFunction<OnClose>;
|
||||
|
||||
const AWS_CREDENTIALS_URL =
|
||||
'http://localhost/api/v1/cloud_integrations/aws/credentials';
|
||||
const AWS_ACCOUNTS_URL =
|
||||
'http://localhost/api/v1/cloud_integrations/aws/accounts';
|
||||
const ACCOUNT_ID = 'ci-aws-1234';
|
||||
|
||||
const credentials = {
|
||||
sigNozApiUrl: 'https://signoz.example.com',
|
||||
sigNozApiKey: 'signoz-api-key',
|
||||
ingestionUrl: 'https://ingest.example.com',
|
||||
ingestionKey: 'ingestion-key',
|
||||
};
|
||||
|
||||
const cliCommand = `curl -fsSL 'https://signoz.io/foundry.sh' | bash -s -- cloudintegration aws cloudformation --region 'us-east-1'`;
|
||||
|
||||
const mockApi = ({ failFirstPoll = false } = {}): {
|
||||
createAccountPayload: unknown;
|
||||
pollCount: () => number;
|
||||
} => {
|
||||
let polls = 0;
|
||||
const api = {
|
||||
createAccountPayload: null as unknown,
|
||||
pollCount: (): number => polls,
|
||||
};
|
||||
|
||||
server.use(
|
||||
rest.get(AWS_CREDENTIALS_URL, (_req, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json({ status: 'success', data: credentials })),
|
||||
),
|
||||
rest.post(AWS_ACCOUNTS_URL, async (req: RestRequest, res, ctx) => {
|
||||
api.createAccountPayload = await req.json();
|
||||
return res(
|
||||
ctx.status(201),
|
||||
ctx.json({
|
||||
status: 'success',
|
||||
data: { id: ACCOUNT_ID, connectionArtifact: { aws: { cliCommand } } },
|
||||
}),
|
||||
);
|
||||
}),
|
||||
rest.get(`${AWS_ACCOUNTS_URL}/${ACCOUNT_ID}`, (_req, res, ctx) => {
|
||||
polls += 1;
|
||||
if (failFirstPoll && polls === 1) {
|
||||
return res(ctx.status(500), ctx.json({ status: 'error' }));
|
||||
}
|
||||
return res(
|
||||
ctx.status(200),
|
||||
ctx.json({
|
||||
status: 'success',
|
||||
data: {
|
||||
id: ACCOUNT_ID,
|
||||
providerAccountId: null,
|
||||
agentReport: null,
|
||||
removedAt: null,
|
||||
},
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
return api;
|
||||
};
|
||||
|
||||
describe('AWS CloudAccountSetupModal', () => {
|
||||
it('creates the account and shows its setup command', async () => {
|
||||
const api = mockApi();
|
||||
const openSpy = jest.spyOn(window, 'open').mockImplementation(() => null);
|
||||
const user = userEvent.setup();
|
||||
const onClose = mockOnClose();
|
||||
|
||||
render(<CloudAccountSetupModal onClose={onClose} />);
|
||||
|
||||
await user.click(await screen.findByRole('combobox'));
|
||||
await user.click(await screen.findByText('US East (N. Virginia)'));
|
||||
await user.click(await screen.findByRole('checkbox', { name: /us-east-1/i }));
|
||||
await user.click(screen.getByTestId('aws-generate-command-btn'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('aws-agent-command')).toHaveTextContent(
|
||||
cliCommand,
|
||||
);
|
||||
});
|
||||
|
||||
expect(api.createAccountPayload).toStrictEqual({
|
||||
config: { aws: { deploymentRegion: 'us-east-1', regions: ['us-east-1'] } },
|
||||
credentials,
|
||||
});
|
||||
expect(
|
||||
screen.queryByTestId('aws-generate-command-btn'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(screen.queryAllByRole('combobox')).toHaveLength(0);
|
||||
expect(screen.getByText(/waiting for connection/i)).toBeInTheDocument();
|
||||
expect(openSpy).not.toHaveBeenCalled();
|
||||
|
||||
openSpy.mockRestore();
|
||||
|
||||
await user.click(screen.getByTestId('aws-cancel-btn'));
|
||||
await user.click(await screen.findByTestId('aws-continue-setup-btn'));
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.queryByTestId('aws-continue-setup-btn'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
|
||||
await user.click(screen.getByTestId('aws-cancel-btn'));
|
||||
await user.click(await screen.findByTestId('aws-close-setup-btn'));
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('closes without asking before a setup command exists', async () => {
|
||||
mockApi();
|
||||
const user = userEvent.setup();
|
||||
const onClose = mockOnClose();
|
||||
|
||||
render(<CloudAccountSetupModal onClose={onClose} />);
|
||||
|
||||
await user.click(await screen.findByTestId('aws-cancel-btn'));
|
||||
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
expect(screen.queryByTestId('aws-close-setup-btn')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('resumes polling with Check Again after the connection check fails', async () => {
|
||||
const api = mockApi({ failFirstPoll: true });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(<CloudAccountSetupModal onClose={mockOnClose()} />);
|
||||
|
||||
await user.click(await screen.findByRole('combobox'));
|
||||
await user.click(await screen.findByText('US East (N. Virginia)'));
|
||||
await user.click(await screen.findByRole('checkbox', { name: /us-east-1/i }));
|
||||
await user.click(screen.getByTestId('aws-generate-command-btn'));
|
||||
|
||||
await user.click(await screen.findByTestId('aws-check-connection-btn'));
|
||||
|
||||
await waitFor(() => expect(api.pollCount()).toBe(2));
|
||||
|
||||
await screen.findByText(/waiting for connection/i);
|
||||
expect(
|
||||
screen.queryByTestId('aws-check-connection-btn'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(screen.getByTestId('aws-agent-command')).toHaveTextContent(cliCommand);
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,23 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
import { ChevronDown, ChevronRight, LoaderCircle } from '@signozhq/icons';
|
||||
import { useCallback, useRef, useState } from 'react';
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import {
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
LoaderCircle,
|
||||
SquareArrowOutUpRight,
|
||||
} from '@signozhq/icons';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Callout } from '@signozhq/ui/callout';
|
||||
import { DrawerWrapper } from '@signozhq/ui/drawer';
|
||||
import { Tabs } from '@signozhq/ui/tabs';
|
||||
import { Form, Select, Spin } from 'antd';
|
||||
import { AZURE_REGIONS } from 'container/Integrations/constants';
|
||||
import { useGetAccount } from 'api/generated/services/cloudintegration';
|
||||
import { CloudintegrationtypesAccountDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import CodeBlock from 'components/CodeBlock/CodeBlock';
|
||||
import {
|
||||
AZURE_REGIONS,
|
||||
INTEGRATION_TYPES,
|
||||
} from 'container/Integrations/constants';
|
||||
import {
|
||||
IntegrationModalProps,
|
||||
ModalStateEnum,
|
||||
@@ -12,13 +25,15 @@ import {
|
||||
import { popupContainer } from 'utils/selectPopupContainer';
|
||||
|
||||
import { useIntegrationModal } from '../../../../../hooks/integration/azure/useIntegrationModal';
|
||||
import AgentSetupCommand from '../../AgentSetupCommand/AgentSetupCommand';
|
||||
import CloseSetupConfirm from '../../CloseSetupConfirm/CloseSetupConfirm';
|
||||
import { useCloseSetupConfirm } from '../../CloseSetupConfirm/useCloseSetupConfirm';
|
||||
import RenderConnectionFields from '../../AmazonWebServices/RegionForm/RenderConnectionParams';
|
||||
|
||||
import '../../AmazonWebServices/AddNewAccount/CloudAccountSetupModal.style.scss';
|
||||
|
||||
const AZURE_CLI_DESC =
|
||||
'Paste the following command if you have Azure CLI setup locally on your machine or use BASH CloudShell on Azure portal with above mentioned permissions.';
|
||||
const AZURE_POWERSHELL_DESC =
|
||||
'Paste the following command in PowerShell CloudShell on Azure portal, you can switch to PowerShell on Azure portal.';
|
||||
|
||||
function CloudAccountSetupModal({
|
||||
onClose,
|
||||
}: IntegrationModalProps): JSX.Element {
|
||||
@@ -26,19 +41,53 @@ function CloudAccountSetupModal({
|
||||
form,
|
||||
modalState,
|
||||
isLoading,
|
||||
connectionCommand,
|
||||
accountId,
|
||||
connectionCommands,
|
||||
handleSubmit,
|
||||
handleClose,
|
||||
connectionParams,
|
||||
isConnectionParamsLoading,
|
||||
checkConnectionAgain,
|
||||
handleConnectionSuccess,
|
||||
handleConnectionTimeout,
|
||||
handleConnectionError,
|
||||
} = useIntegrationModal({ onClose });
|
||||
|
||||
const { isConfirmOpen, setIsConfirmOpen, requestClose } = useCloseSetupConfirm(
|
||||
{ shouldConfirm: Boolean(connectionCommand), onClose: handleClose },
|
||||
);
|
||||
const startTimeRef = useRef(Date.now());
|
||||
const refetchInterval = 10 * 1000;
|
||||
const errorTimeout = 10 * 60 * 1000;
|
||||
|
||||
const [isHowItWorksOpen, setIsHowItWorksOpen] = useState(true);
|
||||
const [activeTab, setActiveTab] = useState('cli');
|
||||
|
||||
useGetAccount(
|
||||
{
|
||||
cloudProvider: INTEGRATION_TYPES.AZURE,
|
||||
id: accountId ?? '',
|
||||
},
|
||||
{
|
||||
query: {
|
||||
enabled: Boolean(accountId) && modalState === ModalStateEnum.WAITING,
|
||||
refetchInterval,
|
||||
select: (response): CloudintegrationtypesAccountDTO => response.data,
|
||||
onSuccess: (account) => {
|
||||
const isConnected =
|
||||
Boolean(account.providerAccountId) && account.removedAt === null;
|
||||
|
||||
if (isConnected) {
|
||||
handleConnectionSuccess({
|
||||
cloudAccountId: account.providerAccountId ?? account.id,
|
||||
status: account.agentReport,
|
||||
});
|
||||
} else if (Date.now() - startTimeRef.current >= errorTimeout) {
|
||||
handleConnectionTimeout({ id: accountId });
|
||||
}
|
||||
},
|
||||
onError: () => {
|
||||
handleConnectionError();
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const renderAlert = useCallback((): JSX.Element | null => {
|
||||
if (modalState === ModalStateEnum.WAITING) {
|
||||
@@ -47,7 +96,14 @@ function CloudAccountSetupModal({
|
||||
<Callout
|
||||
title={
|
||||
<div className="cloud-account-setup-form__alert-message">
|
||||
<Spin indicator={<LoaderCircle size={14} className="animate-spin" />} />
|
||||
<Spin
|
||||
indicator={
|
||||
<LoaderCircle
|
||||
size={14}
|
||||
className="anticon anticon-loading anticon-spin ant-spin-dot"
|
||||
/>
|
||||
}
|
||||
/>
|
||||
Waiting for Azure account connection, retrying in{' '}
|
||||
<span className="retry-time">10</span> secs...
|
||||
</div>
|
||||
@@ -80,233 +136,234 @@ function CloudAccountSetupModal({
|
||||
|
||||
const footer = (
|
||||
<div className="cloud-account-setup-modal__footer">
|
||||
<Button
|
||||
size="md"
|
||||
variant="outlined"
|
||||
color="secondary"
|
||||
onClick={requestClose}
|
||||
testId="azure-cancel-btn"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
{!connectionCommand && (
|
||||
{modalState === ModalStateEnum.FORM && (
|
||||
<Button
|
||||
size="md"
|
||||
variant="solid"
|
||||
color="primary"
|
||||
prefix={<SquareArrowOutUpRight size={17} color={Color.BG_VANILLA_100} />}
|
||||
onClick={handleSubmit}
|
||||
loading={isLoading}
|
||||
testId="azure-generate-command-btn"
|
||||
>
|
||||
Generate Command
|
||||
</Button>
|
||||
)}
|
||||
{modalState === ModalStateEnum.ERROR && connectionCommand && (
|
||||
<Button
|
||||
size="md"
|
||||
variant="solid"
|
||||
color="primary"
|
||||
onClick={checkConnectionAgain}
|
||||
testId="azure-check-connection-btn"
|
||||
>
|
||||
Check Again
|
||||
Generate Azure Setup Commands
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<DrawerWrapper
|
||||
open={true}
|
||||
className="cloud-account-setup-modal"
|
||||
onOpenChange={(open): void => {
|
||||
if (!open) {
|
||||
requestClose();
|
||||
}
|
||||
}}
|
||||
direction="right"
|
||||
showCloseButton
|
||||
title="Add Azure Account"
|
||||
width="wide"
|
||||
footer={footer}
|
||||
>
|
||||
<div className="cloud-account-setup-modal__content">
|
||||
<div className="cloud-account-setup-prerequisites">
|
||||
<div className="cloud-account-setup-prerequisites__title">
|
||||
Prerequisites
|
||||
</div>
|
||||
|
||||
<ul className="cloud-account-setup-prerequisites__list">
|
||||
<li className="cloud-account-setup-prerequisites__list-item">
|
||||
<span className="cloud-account-setup-prerequisites__list-item-bullet">
|
||||
—
|
||||
</span>{' '}
|
||||
<span className="cloud-account-setup-prerequisites__list-item-text">
|
||||
Ensure that you're logged in to the Azure workspace which you want
|
||||
to monitor.
|
||||
</span>
|
||||
</li>
|
||||
<li className="cloud-account-setup-prerequisites__list-item">
|
||||
<span className="cloud-account-setup-prerequisites__list-item-bullet">
|
||||
—
|
||||
</span>{' '}
|
||||
<span className="cloud-account-setup-prerequisites__list-item-text">
|
||||
Ensure that you either have the{' '}
|
||||
<span className="cloud-account-setup-prerequisites__list-item-highlight">
|
||||
Owner
|
||||
</span>{' '}
|
||||
role OR
|
||||
</span>
|
||||
</li>
|
||||
<li className="cloud-account-setup-prerequisites__list-item">
|
||||
<span className="cloud-account-setup-prerequisites__list-item-bullet">
|
||||
—
|
||||
</span>{' '}
|
||||
<span className="cloud-account-setup-prerequisites__list-item-text">
|
||||
Both the{' '}
|
||||
<span className="cloud-account-setup-prerequisites__list-item-highlight">
|
||||
Contributor
|
||||
</span>{' '}
|
||||
and{' '}
|
||||
<span className="cloud-account-setup-prerequisites__list-item-highlight">
|
||||
user access admin
|
||||
</span>{' '}
|
||||
roles
|
||||
</span>
|
||||
</li>
|
||||
</ul>
|
||||
<DrawerWrapper
|
||||
open={true}
|
||||
className="cloud-account-setup-modal"
|
||||
onOpenChange={(open): void => {
|
||||
if (!open) {
|
||||
handleClose();
|
||||
}
|
||||
}}
|
||||
direction="right"
|
||||
showCloseButton
|
||||
title="Add Azure Account"
|
||||
width="wide"
|
||||
footer={footer}
|
||||
>
|
||||
<div className="cloud-account-setup-modal__content">
|
||||
<div className="cloud-account-setup-prerequisites">
|
||||
<div className="cloud-account-setup-prerequisites__title">
|
||||
Prerequisites
|
||||
</div>
|
||||
|
||||
<div className="cloud-account-setup-how-it-works-accordion">
|
||||
<div
|
||||
className={`cloud-account-setup-how-it-works-accordion__title ${
|
||||
isHowItWorksOpen ? 'open' : ''
|
||||
}`}
|
||||
>
|
||||
<Button
|
||||
size="md"
|
||||
variant="link"
|
||||
color="secondary"
|
||||
icon
|
||||
aria-label="How it works"
|
||||
onClick={(): void => setIsHowItWorksOpen(!isHowItWorksOpen)}
|
||||
>
|
||||
{isHowItWorksOpen ? <ChevronDown /> : <ChevronRight />}
|
||||
</Button>
|
||||
|
||||
<span className="cloud-account-setup-how-it-works-accordion__title-text">
|
||||
How it works?
|
||||
<ul className="cloud-account-setup-prerequisites__list">
|
||||
<li className="cloud-account-setup-prerequisites__list-item">
|
||||
<span className="cloud-account-setup-prerequisites__list-item-bullet">
|
||||
—
|
||||
</span>{' '}
|
||||
<span className="cloud-account-setup-prerequisites__list-item-text">
|
||||
Ensure that you're logged in to the Azure workspace which you want
|
||||
to monitor.
|
||||
</span>
|
||||
</li>
|
||||
<li className="cloud-account-setup-prerequisites__list-item">
|
||||
<span className="cloud-account-setup-prerequisites__list-item-bullet">
|
||||
—
|
||||
</span>{' '}
|
||||
<span className="cloud-account-setup-prerequisites__list-item-text">
|
||||
Ensure that you either have the{' '}
|
||||
<span className="cloud-account-setup-prerequisites__list-item-highlight">
|
||||
Owner
|
||||
</span>{' '}
|
||||
role OR
|
||||
</span>
|
||||
</li>
|
||||
<li className="cloud-account-setup-prerequisites__list-item">
|
||||
<span className="cloud-account-setup-prerequisites__list-item-bullet">
|
||||
—
|
||||
</span>{' '}
|
||||
<span className="cloud-account-setup-prerequisites__list-item-text">
|
||||
Both the{' '}
|
||||
<span className="cloud-account-setup-prerequisites__list-item-highlight">
|
||||
Contributor
|
||||
</span>{' '}
|
||||
and{' '}
|
||||
<span className="cloud-account-setup-prerequisites__list-item-highlight">
|
||||
user access admin
|
||||
</span>{' '}
|
||||
roles
|
||||
</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div className="cloud-account-setup-how-it-works-accordion">
|
||||
<div
|
||||
className={`cloud-account-setup-how-it-works-accordion__title ${
|
||||
isHowItWorksOpen ? 'open' : ''
|
||||
}`}
|
||||
>
|
||||
<Button
|
||||
size="md"
|
||||
variant="link"
|
||||
color="secondary"
|
||||
icon
|
||||
aria-label="How it works"
|
||||
onClick={(): void => setIsHowItWorksOpen(!isHowItWorksOpen)}
|
||||
>
|
||||
{isHowItWorksOpen ? <ChevronDown /> : <ChevronRight />}
|
||||
</Button>
|
||||
|
||||
<span className="cloud-account-setup-how-it-works-accordion__title-text">
|
||||
How it works?
|
||||
</span>
|
||||
</div>
|
||||
{isHowItWorksOpen && (
|
||||
<div className="cloud-account-setup-how-it-works-accordion__description">
|
||||
<div className="cloud-account-setup-how-it-works-accordion__description-item">
|
||||
SigNoz will create new resource-group to manage the resources required
|
||||
for this integration. The following steps will create a User-Assigned
|
||||
Managed Identity with the necessary permissions and follows the
|
||||
Principle of Least Privilege.
|
||||
</div>
|
||||
<div className="cloud-account-setup-how-it-works__description-item">
|
||||
Once the Integration template is deployed, you can enable the services
|
||||
you want to monitor right here in Signoz dashboard.
|
||||
</div>
|
||||
</div>
|
||||
{isHowItWorksOpen && (
|
||||
<div className="cloud-account-setup-how-it-works-accordion__description">
|
||||
<div className="cloud-account-setup-how-it-works-accordion__description-item">
|
||||
SigNoz will create new resource-group to manage the resources required
|
||||
for this integration. The following steps will create a User-Assigned
|
||||
Managed Identity with the necessary permissions and follows the
|
||||
Principle of Least Privilege.
|
||||
</div>
|
||||
<div className="cloud-account-setup-how-it-works__description-item">
|
||||
Once the Integration template is deployed, you can enable the services
|
||||
you want to monitor right here in Signoz dashboard.
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Form
|
||||
form={form}
|
||||
className="cloud-account-setup-form"
|
||||
layout="vertical"
|
||||
initialValues={{ resourceGroups: [] }}
|
||||
>
|
||||
<div className="cloud-account-setup-form__content">
|
||||
<div className="cloud-account-setup-form__form-group">
|
||||
<div className="cloud-account-setup-form__title">
|
||||
Where should we deploy the SigNoz collector resources?
|
||||
</div>
|
||||
<div className="cloud-account-setup-form__description">
|
||||
Choose the Azure region for deployment.
|
||||
</div>
|
||||
<Form.Item
|
||||
name="region"
|
||||
rules={[{ required: true, message: 'Please select a region' }]}
|
||||
className="cloud-account-setup-form__form-item"
|
||||
>
|
||||
<Select
|
||||
placeholder="e.g. East US"
|
||||
options={AZURE_REGIONS.map((region) => ({
|
||||
label: `${region.label} (${region.value})`,
|
||||
value: region.value,
|
||||
}))}
|
||||
getPopupContainer={popupContainer}
|
||||
disabled={modalState === ModalStateEnum.WAITING}
|
||||
/>
|
||||
</Form.Item>
|
||||
</div>
|
||||
|
||||
<div className="cloud-account-setup-form__form-group">
|
||||
<div className="cloud-account-setup-form__title">
|
||||
Which resource groups do you want to monitor?
|
||||
</div>
|
||||
<div className="cloud-account-setup-form__description">
|
||||
Add one or more Azure resource group names.
|
||||
</div>
|
||||
<Form.Item
|
||||
name="resourceGroups"
|
||||
rules={[
|
||||
{
|
||||
required: true,
|
||||
type: 'array',
|
||||
min: 1,
|
||||
message: 'Please add at least one resource group',
|
||||
},
|
||||
]}
|
||||
className="cloud-account-setup-form__form-item"
|
||||
>
|
||||
<Select
|
||||
mode="tags"
|
||||
placeholder="e.g. prod-platform-rg"
|
||||
tokenSeparators={[',']}
|
||||
disabled={modalState === ModalStateEnum.WAITING}
|
||||
/>
|
||||
</Form.Item>
|
||||
</div>
|
||||
|
||||
<RenderConnectionFields
|
||||
isConnectionParamsLoading={isConnectionParamsLoading}
|
||||
connectionParams={connectionParams}
|
||||
isFormDisabled={modalState === ModalStateEnum.WAITING}
|
||||
/>
|
||||
|
||||
{connectionCommands && (
|
||||
<div className="cloud-account-setup-form__code-block-tabs-container">
|
||||
<div className="cloud-account-setup-form__code-block-tabs-header">
|
||||
<div className="cloud-account-setup-form__code-block-tabs-header-title">
|
||||
Deploy Agent
|
||||
</div>
|
||||
<div className="cloud-account-setup-form__code-block-tabs-header-description">
|
||||
{activeTab === 'cli' ? AZURE_CLI_DESC : AZURE_POWERSHELL_DESC}
|
||||
</div>
|
||||
</div>
|
||||
<Tabs
|
||||
orientation="horizontal"
|
||||
alignment="start"
|
||||
className="cloud-account-setup-form__code-block-tabs"
|
||||
items={[
|
||||
{
|
||||
key: 'cli',
|
||||
label: 'CLI',
|
||||
children: <CodeBlock code={connectionCommands?.cliCommand || ''} />,
|
||||
},
|
||||
{
|
||||
key: 'powershell',
|
||||
label: 'PowerShell',
|
||||
children: (
|
||||
<CodeBlock
|
||||
code={connectionCommands?.cloudPowerShellCommand || ''}
|
||||
/>
|
||||
),
|
||||
},
|
||||
]}
|
||||
value={activeTab}
|
||||
onChange={(key): void => setActiveTab(key)}
|
||||
variant="primary"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{renderAlert()}
|
||||
|
||||
{modalState === ModalStateEnum.WAITING && (
|
||||
<div className="cloud-account-setup-status-message">
|
||||
After running the command, return here and wait for automatic connection
|
||||
detection.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Form
|
||||
form={form}
|
||||
className="cloud-account-setup-form"
|
||||
layout="vertical"
|
||||
initialValues={{ resourceGroups: [] }}
|
||||
>
|
||||
<div className="cloud-account-setup-form__content">
|
||||
{connectionCommand ? (
|
||||
<AgentSetupCommand
|
||||
description="Run this command in Azure Cloud Shell (Bash), or in a terminal where the Azure CLI is signed in to the subscription you want to monitor. It contains your SigNoz keys, so do not share it."
|
||||
command={connectionCommand}
|
||||
testId="azure-agent-command"
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<div className="cloud-account-setup-form__form-group">
|
||||
<div className="cloud-account-setup-form__title">
|
||||
Where should we deploy the SigNoz collector resources?
|
||||
</div>
|
||||
<div className="cloud-account-setup-form__description">
|
||||
Choose the Azure region for deployment.
|
||||
</div>
|
||||
<Form.Item
|
||||
name="region"
|
||||
rules={[{ required: true, message: 'Please select a region' }]}
|
||||
className="cloud-account-setup-form__form-item"
|
||||
>
|
||||
<Select
|
||||
placeholder="e.g. East US"
|
||||
options={AZURE_REGIONS.map((region) => ({
|
||||
label: `${region.label} (${region.value})`,
|
||||
value: region.value,
|
||||
}))}
|
||||
getPopupContainer={popupContainer}
|
||||
/>
|
||||
</Form.Item>
|
||||
</div>
|
||||
|
||||
<div className="cloud-account-setup-form__form-group">
|
||||
<div className="cloud-account-setup-form__title">
|
||||
Which resource groups do you want to monitor?
|
||||
</div>
|
||||
<div className="cloud-account-setup-form__description">
|
||||
Add one or more Azure resource group names.
|
||||
</div>
|
||||
<Form.Item
|
||||
name="resourceGroups"
|
||||
rules={[
|
||||
{
|
||||
required: true,
|
||||
type: 'array',
|
||||
min: 1,
|
||||
message: 'Please add at least one resource group',
|
||||
},
|
||||
]}
|
||||
className="cloud-account-setup-form__form-item"
|
||||
>
|
||||
<Select
|
||||
mode="tags"
|
||||
placeholder="e.g. prod-platform-rg"
|
||||
tokenSeparators={[',']}
|
||||
/>
|
||||
</Form.Item>
|
||||
</div>
|
||||
|
||||
<RenderConnectionFields
|
||||
isConnectionParamsLoading={isConnectionParamsLoading}
|
||||
connectionParams={connectionParams}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{renderAlert()}
|
||||
|
||||
{modalState === ModalStateEnum.WAITING && (
|
||||
<div className="cloud-account-setup-status-message">
|
||||
After running the command, return here and wait for automatic
|
||||
connection detection.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Form>
|
||||
</div>
|
||||
</DrawerWrapper>
|
||||
<CloseSetupConfirm
|
||||
providerName="Azure"
|
||||
testIdPrefix="azure"
|
||||
open={isConfirmOpen}
|
||||
onOpenChange={setIsConfirmOpen}
|
||||
onConfirm={handleClose}
|
||||
/>
|
||||
</>
|
||||
</Form>
|
||||
</div>
|
||||
</DrawerWrapper>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,175 +0,0 @@
|
||||
import { ComponentProps } from 'react';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { RestRequest } from 'msw';
|
||||
import type logEvent from '../../../../../api/common/logEvent';
|
||||
|
||||
import CloudAccountSetupModal from '../AddNewAccount/CloudAccountSetupModal';
|
||||
|
||||
// `useIntegrationModal` imports logEvent by relative path, which the
|
||||
// jest.config moduleNameMapper (keyed on the `api/common/logEvent` alias) does
|
||||
// not intercept, so mock the resolved module directly.
|
||||
jest.mock('../../../../../api/common/logEvent', () => ({
|
||||
__esModule: true,
|
||||
default: jest.fn() as jest.MockedFunction<typeof logEvent>,
|
||||
}));
|
||||
|
||||
// The form flow drives antd selects and typing, which outruns the 5s default on CI.
|
||||
jest.setTimeout(15_000);
|
||||
|
||||
type OnClose = ComponentProps<typeof CloudAccountSetupModal>['onClose'];
|
||||
|
||||
const mockOnClose = (): jest.MockedFunction<OnClose> =>
|
||||
jest.fn() as jest.MockedFunction<OnClose>;
|
||||
|
||||
const AZURE_CREDENTIALS_URL =
|
||||
'http://localhost/api/v1/cloud_integrations/azure/credentials';
|
||||
const AZURE_ACCOUNTS_URL =
|
||||
'http://localhost/api/v1/cloud_integrations/azure/accounts';
|
||||
const ACCOUNT_ID = 'ci-azure-1234';
|
||||
|
||||
const credentials = {
|
||||
sigNozApiUrl: 'https://signoz.example.com',
|
||||
sigNozApiKey: 'signoz-api-key',
|
||||
ingestionUrl: 'https://ingest.example.com',
|
||||
ingestionKey: 'ingestion-key',
|
||||
};
|
||||
|
||||
const cliCommand = `curl -fsSL 'https://signoz.io/foundry.sh' | bash -s -- cloudintegration azure bicep --region 'australiaeast'`;
|
||||
|
||||
const mockApi = ({ failFirstPoll = false } = {}): {
|
||||
createAccountPayload: unknown;
|
||||
pollCount: () => number;
|
||||
} => {
|
||||
let polls = 0;
|
||||
const api = {
|
||||
createAccountPayload: null as unknown,
|
||||
pollCount: (): number => polls,
|
||||
};
|
||||
|
||||
server.use(
|
||||
rest.get(AZURE_CREDENTIALS_URL, (_req, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json({ status: 'success', data: credentials })),
|
||||
),
|
||||
rest.post(AZURE_ACCOUNTS_URL, async (req: RestRequest, res, ctx) => {
|
||||
api.createAccountPayload = await req.json();
|
||||
return res(
|
||||
ctx.status(201),
|
||||
ctx.json({
|
||||
status: 'success',
|
||||
data: { id: ACCOUNT_ID, connectionArtifact: { azure: { cliCommand } } },
|
||||
}),
|
||||
);
|
||||
}),
|
||||
rest.get(`${AZURE_ACCOUNTS_URL}/${ACCOUNT_ID}`, (_req, res, ctx) => {
|
||||
polls += 1;
|
||||
if (failFirstPoll && polls === 1) {
|
||||
return res(ctx.status(500), ctx.json({ status: 'error' }));
|
||||
}
|
||||
return res(
|
||||
ctx.status(200),
|
||||
ctx.json({
|
||||
status: 'success',
|
||||
data: {
|
||||
id: ACCOUNT_ID,
|
||||
providerAccountId: null,
|
||||
agentReport: null,
|
||||
removedAt: null,
|
||||
},
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
return api;
|
||||
};
|
||||
|
||||
describe('Azure CloudAccountSetupModal', () => {
|
||||
it('creates the account and shows its setup command', async () => {
|
||||
const api = mockApi();
|
||||
const user = userEvent.setup();
|
||||
const onClose = mockOnClose();
|
||||
|
||||
render(<CloudAccountSetupModal onClose={onClose} />);
|
||||
|
||||
const [region, resourceGroups] = await screen.findAllByRole('combobox');
|
||||
await user.click(region);
|
||||
await user.click(await screen.findByText('Australia East (australiaeast)'));
|
||||
await user.type(resourceGroups, 'prod-platform-rg{Enter}');
|
||||
await user.click(screen.getByTestId('azure-generate-command-btn'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('azure-agent-command')).toHaveTextContent(
|
||||
cliCommand,
|
||||
);
|
||||
});
|
||||
|
||||
expect(api.createAccountPayload).toStrictEqual({
|
||||
config: {
|
||||
azure: {
|
||||
deploymentRegion: 'australiaeast',
|
||||
resourceGroups: ['prod-platform-rg'],
|
||||
},
|
||||
},
|
||||
credentials,
|
||||
});
|
||||
expect(
|
||||
screen.queryByTestId('azure-generate-command-btn'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(screen.queryAllByRole('combobox')).toHaveLength(0);
|
||||
expect(
|
||||
screen.getByText(/waiting for azure account connection/i),
|
||||
).toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getByTestId('azure-cancel-btn'));
|
||||
await user.click(await screen.findByTestId('azure-continue-setup-btn'));
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.queryByTestId('azure-continue-setup-btn'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
|
||||
await user.click(screen.getByTestId('azure-cancel-btn'));
|
||||
await user.click(await screen.findByTestId('azure-close-setup-btn'));
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('closes without asking before a setup command exists', async () => {
|
||||
mockApi();
|
||||
const user = userEvent.setup();
|
||||
const onClose = mockOnClose();
|
||||
|
||||
render(<CloudAccountSetupModal onClose={onClose} />);
|
||||
|
||||
await user.click(await screen.findByTestId('azure-cancel-btn'));
|
||||
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
expect(screen.queryByTestId('azure-close-setup-btn')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('resumes polling with Check Again after the connection check fails', async () => {
|
||||
const api = mockApi({ failFirstPoll: true });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(<CloudAccountSetupModal onClose={mockOnClose()} />);
|
||||
|
||||
const [region, resourceGroups] = await screen.findAllByRole('combobox');
|
||||
await user.click(region);
|
||||
await user.click(await screen.findByText('Australia East (australiaeast)'));
|
||||
await user.type(resourceGroups, 'prod-platform-rg{Enter}');
|
||||
await user.click(screen.getByTestId('azure-generate-command-btn'));
|
||||
|
||||
await user.click(await screen.findByTestId('azure-check-connection-btn'));
|
||||
|
||||
await waitFor(() => expect(api.pollCount()).toBe(2));
|
||||
|
||||
await screen.findByText(/waiting for azure account connection/i);
|
||||
expect(
|
||||
screen.queryByTestId('azure-check-connection-btn'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(screen.getByTestId('azure-agent-command')).toHaveTextContent(
|
||||
cliCommand,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,59 +0,0 @@
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { DialogWrapper } from '@signozhq/ui/dialog';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
|
||||
interface CloseSetupConfirmProps {
|
||||
/** Provider name as shown in the title, e.g. `AWS`. */
|
||||
providerName: string;
|
||||
/** Prefix for the dialog's test ids, e.g. `aws`. */
|
||||
testIdPrefix: string;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onConfirm: () => void;
|
||||
}
|
||||
|
||||
function CloseSetupConfirm({
|
||||
providerName,
|
||||
testIdPrefix,
|
||||
open,
|
||||
onOpenChange,
|
||||
onConfirm,
|
||||
}: CloseSetupConfirmProps): JSX.Element {
|
||||
return (
|
||||
<DialogWrapper
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
title={`Close ${providerName} agent setup?`}
|
||||
testId={`${testIdPrefix}-close-setup-confirm`}
|
||||
footer={
|
||||
<>
|
||||
<Button
|
||||
size="md"
|
||||
variant="solid"
|
||||
color="highlight-danger"
|
||||
onClick={onConfirm}
|
||||
testId={`${testIdPrefix}-close-setup-btn`}
|
||||
>
|
||||
Close Setup
|
||||
</Button>
|
||||
<Button
|
||||
size="md"
|
||||
variant="solid"
|
||||
color="primary"
|
||||
onClick={(): void => onOpenChange(false)}
|
||||
testId={`${testIdPrefix}-continue-setup-btn`}
|
||||
>
|
||||
Continue Setup
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<Typography>
|
||||
The agent has not connected yet. If you close now, you will have to start
|
||||
the installation process again with a new setup command.
|
||||
</Typography>
|
||||
</DialogWrapper>
|
||||
);
|
||||
}
|
||||
|
||||
export default CloseSetupConfirm;
|
||||
@@ -1,30 +0,0 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
|
||||
interface UseCloseSetupConfirmProps {
|
||||
/** True once closing would lose a pending setup, i.e. a setup command exists. */
|
||||
shouldConfirm: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
interface UseCloseSetupConfirm {
|
||||
isConfirmOpen: boolean;
|
||||
setIsConfirmOpen: (open: boolean) => void;
|
||||
requestClose: () => void;
|
||||
}
|
||||
|
||||
export function useCloseSetupConfirm({
|
||||
shouldConfirm,
|
||||
onClose,
|
||||
}: UseCloseSetupConfirmProps): UseCloseSetupConfirm {
|
||||
const [isConfirmOpen, setIsConfirmOpen] = useState(false);
|
||||
|
||||
const requestClose = useCallback((): void => {
|
||||
if (shouldConfirm) {
|
||||
setIsConfirmOpen(true);
|
||||
return;
|
||||
}
|
||||
onClose();
|
||||
}, [shouldConfirm, onClose]);
|
||||
|
||||
return { isConfirmOpen, setIsConfirmOpen, requestClose };
|
||||
}
|
||||
@@ -3,7 +3,3 @@
|
||||
align-items: center;
|
||||
gap: var(--spacing-4);
|
||||
}
|
||||
|
||||
.mono {
|
||||
composes: mono from '../shared.module.scss';
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ import { ModalStateEnum } from 'container/Integrations/HeroSection/types';
|
||||
import { useAgentAccountSetup } from 'hooks/integration/gcp/useAgentAccountSetup';
|
||||
import { useForm } from 'react-hook-form';
|
||||
|
||||
import AgentSetupCommand from 'container/Integrations/CloudIntegration/AgentSetupCommand/AgentSetupCommand';
|
||||
import ConnectionMethodSelector from '../ConnectionMethodSelector';
|
||||
import ConnectionSecretsFields from '../ConnectionSecretsFields';
|
||||
import { AGENT_SETUP_GUIDE, DEFAULT_SETUP_FORM_VALUES } from '../constants';
|
||||
@@ -16,6 +15,7 @@ import SetupDrawerFooter from '../SetupDrawerFooter';
|
||||
import SetupGuideCallout from '../SetupGuideCallout';
|
||||
import { GcpSetupFormValues } from '../types';
|
||||
import { usePrefillCredentials } from '../usePrefillCredentials';
|
||||
import AgentSetupCommand from './AgentSetupCommand';
|
||||
|
||||
import styles from './AgentSetup.module.scss';
|
||||
|
||||
@@ -67,15 +67,8 @@ function AgentSetup({
|
||||
{connectionCommand ? (
|
||||
<>
|
||||
<AgentSetupCommand
|
||||
description={
|
||||
<>
|
||||
Run this command in Google Cloud Shell, or in a terminal where gcloud is
|
||||
signed in to <span className={styles.mono}>{commandProjectId}</span>. It
|
||||
contains your SigNoz keys, so do not share it.
|
||||
</>
|
||||
}
|
||||
deploymentProjectId={commandProjectId}
|
||||
command={connectionCommand}
|
||||
testId="gcp-agent-command"
|
||||
/>
|
||||
{modalState === ModalStateEnum.WAITING && (
|
||||
<Callout
|
||||
|
||||
@@ -10,6 +10,10 @@
|
||||
gap: var(--spacing-3);
|
||||
}
|
||||
|
||||
.mono {
|
||||
composes: mono from '../shared.module.scss';
|
||||
}
|
||||
|
||||
// CodeBlock renders the copy button's wrapper first and the highlighted code last;
|
||||
// the code theme sets the block's margin and padding inline, hence !important.
|
||||
.command {
|
||||
@@ -1,28 +1,27 @@
|
||||
import { ReactNode } from 'react';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import CodeBlock from 'components/CodeBlock/CodeBlock';
|
||||
|
||||
import styles from './AgentSetupCommand.module.scss';
|
||||
|
||||
interface AgentSetupCommandProps {
|
||||
description: ReactNode;
|
||||
deploymentProjectId: string;
|
||||
command: string;
|
||||
testId: string;
|
||||
}
|
||||
|
||||
function AgentSetupCommand({
|
||||
description,
|
||||
deploymentProjectId,
|
||||
command,
|
||||
testId,
|
||||
}: AgentSetupCommandProps): JSX.Element {
|
||||
return (
|
||||
<div className={styles.commands} data-testid={testId}>
|
||||
<div className={styles.commands} data-testid="gcp-agent-command">
|
||||
<div className={styles.commandsHead}>
|
||||
<Typography.Text weight="bold" size="base">
|
||||
Deploy the SigNoz agent
|
||||
</Typography.Text>
|
||||
<Typography.Text as="p" size="small" color="muted">
|
||||
{description}
|
||||
Run this command in Google Cloud Shell, or in a terminal where gcloud is
|
||||
signed in to <span className={styles.mono}>{deploymentProjectId}</span>. It
|
||||
contains your SigNoz keys, so do not share it.
|
||||
</Typography.Text>
|
||||
</div>
|
||||
<CodeBlock language="bash" code={command} className={styles.command} />
|
||||
@@ -1,9 +1,10 @@
|
||||
import { useState } from 'react';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { DialogWrapper } from '@signozhq/ui/dialog';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import { CloudintegrationtypesGCPConnectionMethodDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { IntegrationModalProps } from 'container/Integrations/HeroSection/types';
|
||||
|
||||
import CloseSetupConfirm from '../../CloseSetupConfirm/CloseSetupConfirm';
|
||||
import { useCloseSetupConfirm } from '../../CloseSetupConfirm/useCloseSetupConfirm';
|
||||
import AgentSetup from './AgentSetup/AgentSetup';
|
||||
import ManualSetup from './ManualSetup/ManualSetup';
|
||||
import SetupDrawerLayout from './SetupDrawerLayout';
|
||||
@@ -17,9 +18,15 @@ function CloudAccountSetupDrawer({
|
||||
);
|
||||
// Set once the agent command exists; closing after that loses the pending setup.
|
||||
const [hasGeneratedCommand, setHasGeneratedCommand] = useState(false);
|
||||
const { isConfirmOpen, setIsConfirmOpen, requestClose } = useCloseSetupConfirm(
|
||||
{ shouldConfirm: hasGeneratedCommand, onClose },
|
||||
);
|
||||
const [isCloseConfirmOpen, setIsCloseConfirmOpen] = useState(false);
|
||||
|
||||
const requestClose = (): void => {
|
||||
if (hasGeneratedCommand) {
|
||||
setIsCloseConfirmOpen(true);
|
||||
return;
|
||||
}
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -42,13 +49,39 @@ function CloudAccountSetupDrawer({
|
||||
)
|
||||
}
|
||||
</SetupDrawerLayout>
|
||||
<CloseSetupConfirm
|
||||
providerName="GCP"
|
||||
testIdPrefix="gcp"
|
||||
open={isConfirmOpen}
|
||||
onOpenChange={setIsConfirmOpen}
|
||||
onConfirm={onClose}
|
||||
/>
|
||||
<DialogWrapper
|
||||
open={isCloseConfirmOpen}
|
||||
onOpenChange={setIsCloseConfirmOpen}
|
||||
title="Close GCP agent setup?"
|
||||
testId="gcp-close-setup-confirm"
|
||||
footer={
|
||||
<>
|
||||
<Button
|
||||
size="md"
|
||||
variant="solid"
|
||||
color="highlight-danger"
|
||||
onClick={onClose}
|
||||
testId="gcp-close-setup-btn"
|
||||
>
|
||||
Close Setup
|
||||
</Button>
|
||||
<Button
|
||||
size="md"
|
||||
variant="solid"
|
||||
color="primary"
|
||||
onClick={(): void => setIsCloseConfirmOpen(false)}
|
||||
testId="gcp-continue-setup-btn"
|
||||
>
|
||||
Continue Setup
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<Typography>
|
||||
The agent has not connected yet. If you close now, you will have to start
|
||||
the installation process again with a new setup command.
|
||||
</Typography>
|
||||
</DialogWrapper>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -20,12 +20,18 @@ export interface RegionFormProps {
|
||||
includeAllRegions: boolean;
|
||||
onRegionSelect: () => void;
|
||||
onSubmit: () => Promise<void>;
|
||||
connectionCommand: string | null;
|
||||
accountId?: string;
|
||||
handleRegionChange: (value: string) => void;
|
||||
connectionParams?: CloudintegrationtypesCredentialsDTO;
|
||||
isConnectionParamsLoading?: boolean;
|
||||
setSelectedRegions: Dispatch<SetStateAction<string[]>>;
|
||||
setIncludeAllRegions: Dispatch<SetStateAction<boolean>>;
|
||||
onConnectionSuccess: (payload: {
|
||||
cloudAccountId: string;
|
||||
status?: unknown;
|
||||
}) => void;
|
||||
onConnectionTimeout: (payload: { id?: string }) => void;
|
||||
onConnectionError: () => void;
|
||||
}
|
||||
|
||||
export interface IntegrationModalProps {
|
||||
|
||||
@@ -14,10 +14,9 @@ import {
|
||||
GetConnectionCredentialsQueryResult,
|
||||
invalidateListAccounts,
|
||||
useCreateAccount,
|
||||
useGetConnectionCredentials,
|
||||
} from 'api/generated/services/cloudintegration';
|
||||
import { useGetConnectionCredentials } from 'api/generated/services/cloudintegration';
|
||||
import {
|
||||
CloudintegrationtypesAccountDTO,
|
||||
CloudintegrationtypesCredentialsDTO,
|
||||
CloudintegrationtypesPostableAccountDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
@@ -30,7 +29,6 @@ import useAxiosError from 'hooks/useAxiosError';
|
||||
import { regions } from 'utils/regions';
|
||||
|
||||
import logEvent from '../../../api/common/logEvent';
|
||||
import { useAgentConnectionPolling } from '../useAgentConnectionPolling';
|
||||
|
||||
interface UseIntegrationModalProps {
|
||||
onClose: () => void;
|
||||
@@ -44,8 +42,7 @@ interface UseIntegrationModal {
|
||||
activeView: ActiveViewEnum;
|
||||
selectedRegions: string[];
|
||||
includeAllRegions: boolean;
|
||||
isGeneratingCommand: boolean;
|
||||
connectionCommand: string | null;
|
||||
isGeneratingUrl: boolean;
|
||||
setSelectedRegions: Dispatch<SetStateAction<string[]>>;
|
||||
setIncludeAllRegions: Dispatch<SetStateAction<boolean>>;
|
||||
handleRegionSelect: () => void;
|
||||
@@ -53,11 +50,17 @@ interface UseIntegrationModal {
|
||||
handleClose: () => void;
|
||||
setActiveView: (view: ActiveViewEnum) => void;
|
||||
allRegions: string[];
|
||||
accountId?: string;
|
||||
selectedDeploymentRegion: string | undefined;
|
||||
handleRegionChange: (value: string) => void;
|
||||
connectionParams?: CloudintegrationtypesCredentialsDTO;
|
||||
isConnectionParamsLoading: boolean;
|
||||
checkConnectionAgain: () => void;
|
||||
handleConnectionSuccess: (payload: {
|
||||
cloudAccountId: string;
|
||||
status?: unknown;
|
||||
}) => void;
|
||||
handleConnectionTimeout: (payload: { id?: string }) => void;
|
||||
handleConnectionError: () => void;
|
||||
}
|
||||
|
||||
export function useIntegrationModal({
|
||||
@@ -70,9 +73,6 @@ export function useIntegrationModal({
|
||||
);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [accountId, setAccountId] = useState<string | undefined>();
|
||||
const [connectionCommand, setConnectionCommand] = useState<string | null>(
|
||||
null,
|
||||
);
|
||||
const [activeView, setActiveView] = useState<ActiveViewEnum>(
|
||||
ActiveViewEnum.FORM,
|
||||
);
|
||||
@@ -103,15 +103,14 @@ export function useIntegrationModal({
|
||||
setSelectedRegions([]);
|
||||
setIncludeAllRegions(false);
|
||||
setModalState(ModalStateEnum.FORM);
|
||||
setConnectionCommand(null);
|
||||
onClose();
|
||||
}, [onClose]);
|
||||
|
||||
const handleConnectionSuccess = useCallback(
|
||||
(account: CloudintegrationtypesAccountDTO): void => {
|
||||
(payload: { cloudAccountId: string; status?: unknown }): void => {
|
||||
void logEvent('AWS Integration: Account connected', {
|
||||
cloudAccountId: account.providerAccountId ?? account.id,
|
||||
status: account.agentReport,
|
||||
cloudAccountId: payload.cloudAccountId,
|
||||
status: payload.status,
|
||||
});
|
||||
toast.success('AWS account connected successfully', {
|
||||
position: 'bottom-right',
|
||||
@@ -124,32 +123,21 @@ export function useIntegrationModal({
|
||||
[handleClose, queryClient],
|
||||
);
|
||||
|
||||
const handleConnectionTimeout = useCallback((): void => {
|
||||
setModalState(ModalStateEnum.ERROR);
|
||||
void logEvent('AWS Integration: Account connection attempt timed out', {
|
||||
id: accountId,
|
||||
});
|
||||
}, [accountId]);
|
||||
const handleConnectionTimeout = useCallback(
|
||||
(payload: { id?: string }): void => {
|
||||
setModalState(ModalStateEnum.ERROR);
|
||||
void logEvent('AWS Integration: Account connection attempt timed out', {
|
||||
id: payload.id,
|
||||
});
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const handleConnectionError = useCallback((): void => {
|
||||
setModalState(ModalStateEnum.ERROR);
|
||||
}, []);
|
||||
|
||||
const checkConnectionAgain = useCallback((): void => {
|
||||
setModalState(ModalStateEnum.WAITING);
|
||||
}, []);
|
||||
|
||||
useAgentConnectionPolling({
|
||||
cloudProvider: INTEGRATION_TYPES.AWS,
|
||||
accountId: accountId ?? '',
|
||||
enabled: modalState === ModalStateEnum.WAITING && accountId !== undefined,
|
||||
onConnected: handleConnectionSuccess,
|
||||
onTimeout: handleConnectionTimeout,
|
||||
onError: handleConnectionError,
|
||||
});
|
||||
|
||||
const { mutate: createAccount, isLoading: isGeneratingCommand } =
|
||||
useCreateAccount();
|
||||
const { mutate: generateUrl, isLoading: isGeneratingUrl } = useCreateAccount();
|
||||
|
||||
const handleError = useAxiosError();
|
||||
const { data: connectionParams, isLoading: isConnectionParamsLoading } =
|
||||
@@ -164,9 +152,9 @@ export function useIntegrationModal({
|
||||
},
|
||||
);
|
||||
|
||||
const handleGenerateCommand = useCallback(
|
||||
const handleGenerateUrl = useCallback(
|
||||
(payload: CloudintegrationtypesPostableAccountDTO): void => {
|
||||
createAccount(
|
||||
generateUrl(
|
||||
{
|
||||
pathParams: { cloudProvider: INTEGRATION_TYPES.AWS },
|
||||
data: payload,
|
||||
@@ -174,19 +162,17 @@ export function useIntegrationModal({
|
||||
{
|
||||
onSuccess: (response: CreateAccountMutationResult) => {
|
||||
const accountId = response.data.id;
|
||||
const command = response.data.connectionArtifact.aws?.cliCommand;
|
||||
if (!command) {
|
||||
setModalState(ModalStateEnum.ERROR);
|
||||
toast.error('Failed to generate the AWS setup command', {
|
||||
position: 'bottom-right',
|
||||
});
|
||||
return;
|
||||
}
|
||||
const connectionUrl =
|
||||
response.data.connectionArtifact.aws?.connectionUrl ?? '';
|
||||
|
||||
void logEvent('AWS Integration: Account connection command generated', {
|
||||
id: accountId,
|
||||
});
|
||||
setConnectionCommand(command);
|
||||
void logEvent(
|
||||
'AWS Integration: Account connection attempt redirected to AWS',
|
||||
{
|
||||
id: accountId,
|
||||
},
|
||||
);
|
||||
// oxlint-disable-next-line signoz/no-raw-absolute-path -- connectionUrl is an external AWS console URL, not an internal path
|
||||
window.open(connectionUrl, '_blank');
|
||||
setModalState(ModalStateEnum.WAITING);
|
||||
setAccountId(accountId);
|
||||
},
|
||||
@@ -199,7 +185,7 @@ export function useIntegrationModal({
|
||||
},
|
||||
);
|
||||
},
|
||||
[createAccount],
|
||||
[generateUrl],
|
||||
);
|
||||
|
||||
const handleSubmit = useCallback(async (): Promise<void> => {
|
||||
@@ -222,13 +208,13 @@ export function useIntegrationModal({
|
||||
},
|
||||
};
|
||||
|
||||
handleGenerateCommand(payload);
|
||||
handleGenerateUrl(payload);
|
||||
} catch (error) {
|
||||
console.error('Form submission failed:', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [form, selectedRegions, handleGenerateCommand, connectionParams]);
|
||||
}, [form, selectedRegions, handleGenerateUrl, connectionParams]);
|
||||
|
||||
return {
|
||||
form,
|
||||
@@ -237,8 +223,7 @@ export function useIntegrationModal({
|
||||
activeView,
|
||||
selectedRegions,
|
||||
includeAllRegions,
|
||||
isGeneratingCommand,
|
||||
connectionCommand,
|
||||
isGeneratingUrl,
|
||||
setSelectedRegions,
|
||||
setIncludeAllRegions,
|
||||
handleRegionSelect,
|
||||
@@ -246,6 +231,7 @@ export function useIntegrationModal({
|
||||
handleClose,
|
||||
setActiveView,
|
||||
allRegions,
|
||||
accountId,
|
||||
setModalState,
|
||||
selectedDeploymentRegion,
|
||||
handleRegionChange,
|
||||
@@ -253,6 +239,8 @@ export function useIntegrationModal({
|
||||
| CloudintegrationtypesCredentialsDTO
|
||||
| undefined,
|
||||
isConnectionParamsLoading,
|
||||
checkConnectionAgain,
|
||||
handleConnectionSuccess,
|
||||
handleConnectionTimeout,
|
||||
handleConnectionError,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
useGetConnectionCredentials,
|
||||
} from 'api/generated/services/cloudintegration';
|
||||
import {
|
||||
CloudintegrationtypesAccountDTO,
|
||||
CloudintegrationtypesCredentialsDTO,
|
||||
CloudintegrationtypesPostableAccountDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
@@ -19,7 +18,6 @@ import { ModalStateEnum } from 'container/Integrations/HeroSection/types';
|
||||
import useAxiosError from 'hooks/useAxiosError';
|
||||
|
||||
import logEvent from '../../../api/common/logEvent';
|
||||
import { useAgentConnectionPolling } from '../useAgentConnectionPolling';
|
||||
|
||||
interface UseIntegrationModalProps {
|
||||
onClose: () => void;
|
||||
@@ -29,13 +27,22 @@ interface UseAzureIntegrationModal {
|
||||
form: FormInstance;
|
||||
modalState: ModalStateEnum;
|
||||
isLoading: boolean;
|
||||
connectionCommand: string | null;
|
||||
accountId?: string;
|
||||
connectionCommands: {
|
||||
cliCommand: string;
|
||||
cloudPowerShellCommand: string;
|
||||
} | null;
|
||||
setModalState: Dispatch<SetStateAction<ModalStateEnum>>;
|
||||
handleSubmit: () => Promise<void>;
|
||||
handleClose: () => void;
|
||||
connectionParams?: CloudintegrationtypesCredentialsDTO;
|
||||
isConnectionParamsLoading: boolean;
|
||||
checkConnectionAgain: () => void;
|
||||
handleConnectionSuccess: (payload: {
|
||||
cloudAccountId: string;
|
||||
status?: unknown;
|
||||
}) => void;
|
||||
handleConnectionTimeout: (payload: { id?: string }) => void;
|
||||
handleConnectionError: () => void;
|
||||
}
|
||||
|
||||
export function useIntegrationModal({
|
||||
@@ -48,21 +55,22 @@ export function useIntegrationModal({
|
||||
);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [accountId, setAccountId] = useState<string | undefined>(undefined);
|
||||
const [connectionCommand, setConnectionCommand] = useState<string | null>(
|
||||
null,
|
||||
);
|
||||
const [connectionCommands, setConnectionCommands] = useState<{
|
||||
cliCommand: string;
|
||||
cloudPowerShellCommand: string;
|
||||
} | null>(null);
|
||||
|
||||
const handleClose = useCallback((): void => {
|
||||
setModalState(ModalStateEnum.FORM);
|
||||
setConnectionCommand(null);
|
||||
setConnectionCommands(null);
|
||||
onClose();
|
||||
}, [onClose]);
|
||||
|
||||
const handleConnectionSuccess = useCallback(
|
||||
(account: CloudintegrationtypesAccountDTO): void => {
|
||||
void logEvent('Azure Integration: Account connected', {
|
||||
cloudAccountId: account.providerAccountId ?? account.id,
|
||||
status: account.agentReport,
|
||||
(payload: { cloudAccountId: string; status?: unknown }): void => {
|
||||
logEvent('Azure Integration: Account connected', {
|
||||
cloudAccountId: payload.cloudAccountId,
|
||||
status: payload.status,
|
||||
});
|
||||
toast.success('Azure account connected successfully', {
|
||||
position: 'bottom-right',
|
||||
@@ -75,30 +83,20 @@ export function useIntegrationModal({
|
||||
[handleClose, queryClient],
|
||||
);
|
||||
|
||||
const handleConnectionTimeout = useCallback((): void => {
|
||||
setModalState(ModalStateEnum.ERROR);
|
||||
void logEvent('Azure Integration: Account connection attempt timed out', {
|
||||
id: accountId,
|
||||
});
|
||||
}, [accountId]);
|
||||
const handleConnectionTimeout = useCallback(
|
||||
(payload: { id?: string }): void => {
|
||||
setModalState(ModalStateEnum.ERROR);
|
||||
logEvent('Azure Integration: Account connection attempt timed out', {
|
||||
id: payload.id,
|
||||
});
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const handleConnectionError = useCallback((): void => {
|
||||
setModalState(ModalStateEnum.ERROR);
|
||||
}, []);
|
||||
|
||||
const checkConnectionAgain = useCallback((): void => {
|
||||
setModalState(ModalStateEnum.WAITING);
|
||||
}, []);
|
||||
|
||||
useAgentConnectionPolling({
|
||||
cloudProvider: INTEGRATION_TYPES.AZURE,
|
||||
accountId: accountId ?? '',
|
||||
enabled: modalState === ModalStateEnum.WAITING && accountId !== undefined,
|
||||
onConnected: handleConnectionSuccess,
|
||||
onTimeout: handleConnectionTimeout,
|
||||
onError: handleConnectionError,
|
||||
});
|
||||
|
||||
const { mutate: createAccount } = useCreateAccount();
|
||||
const handleError = useAxiosError();
|
||||
|
||||
@@ -142,20 +140,16 @@ export function useIntegrationModal({
|
||||
{
|
||||
onSuccess: (response: CreateAccountMutationResult) => {
|
||||
const nextAccountId = response.data.id;
|
||||
const command = response.data.connectionArtifact.azure?.cliCommand;
|
||||
if (!command) {
|
||||
setModalState(ModalStateEnum.ERROR);
|
||||
toast.error('Failed to generate the Azure setup command', {
|
||||
position: 'bottom-right',
|
||||
});
|
||||
return;
|
||||
}
|
||||
const artifact = response.data.connectionArtifact.azure;
|
||||
|
||||
void logEvent('Azure Integration: Account connection command generated', {
|
||||
logEvent('Azure Integration: Account connection commands generated', {
|
||||
id: nextAccountId,
|
||||
});
|
||||
|
||||
setConnectionCommand(command);
|
||||
setConnectionCommands({
|
||||
cliCommand: artifact?.cliCommand || '',
|
||||
cloudPowerShellCommand: artifact?.cloudPowerShellCommand || '',
|
||||
});
|
||||
setModalState(ModalStateEnum.WAITING);
|
||||
setAccountId(nextAccountId);
|
||||
},
|
||||
@@ -178,7 +172,8 @@ export function useIntegrationModal({
|
||||
form,
|
||||
modalState,
|
||||
isLoading,
|
||||
connectionCommand,
|
||||
accountId,
|
||||
connectionCommands,
|
||||
setModalState,
|
||||
handleSubmit,
|
||||
handleClose,
|
||||
@@ -186,6 +181,8 @@ export function useIntegrationModal({
|
||||
| CloudintegrationtypesCredentialsDTO
|
||||
| undefined,
|
||||
isConnectionParamsLoading,
|
||||
checkConnectionAgain,
|
||||
handleConnectionSuccess,
|
||||
handleConnectionTimeout,
|
||||
handleConnectionError,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -22,7 +22,6 @@ const renderPolling = (): void => {
|
||||
renderHook(
|
||||
() =>
|
||||
useAgentConnectionPolling({
|
||||
cloudProvider: 'gcp',
|
||||
accountId: ACCOUNT_ID,
|
||||
enabled: true,
|
||||
...callbacks,
|
||||
@@ -21,7 +21,6 @@ const renderPolling = (
|
||||
const { rerender } = renderHook(
|
||||
({ enabled }: { enabled: boolean }) =>
|
||||
useAgentConnectionPolling({
|
||||
cloudProvider: 'gcp',
|
||||
accountId: ACCOUNT_ID,
|
||||
enabled,
|
||||
...callbacks,
|
||||
@@ -5,11 +5,10 @@ import {
|
||||
CloudintegrationtypesGCPConnectionMethodDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { GcpSetupFormValues } from 'container/Integrations/CloudIntegration/GoogleCloudPlatform/AddNewAccount/types';
|
||||
import { INTEGRATION_TYPES } from 'container/Integrations/constants';
|
||||
import { ModalStateEnum } from 'container/Integrations/HeroSection/types';
|
||||
|
||||
import logEvent from '../../../api/common/logEvent';
|
||||
import { useAgentConnectionPolling } from '../useAgentConnectionPolling';
|
||||
import { useAgentConnectionPolling } from './useAgentConnectionPolling';
|
||||
import { useGcpAccountSetup } from './useGcpAccountSetup';
|
||||
|
||||
const GENERATE_COMMAND_ERROR = 'Failed to generate the GCP setup command';
|
||||
@@ -117,7 +116,6 @@ export function useAgentAccountSetup({
|
||||
}, []);
|
||||
|
||||
useAgentConnectionPolling({
|
||||
cloudProvider: INTEGRATION_TYPES.GCP,
|
||||
accountId: accountId ?? '',
|
||||
enabled: modalState === ModalStateEnum.WAITING && accountId !== null,
|
||||
onConnected: handleAgentConnected,
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useGetAccount } from 'api/generated/services/cloudintegration';
|
||||
import { CloudintegrationtypesAccountDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { INTEGRATION_TYPES } from 'container/Integrations/constants';
|
||||
|
||||
export const POLL_INTERVAL_MS = 10 * 1000;
|
||||
export const CONNECTION_TIMEOUT_MS = 10 * 60 * 1000;
|
||||
|
||||
interface UseAgentConnectionPollingProps {
|
||||
cloudProvider: string;
|
||||
accountId: string;
|
||||
/** Polls exactly while true; the caller decides when there is an account to poll. */
|
||||
enabled: boolean;
|
||||
@@ -16,11 +16,10 @@ interface UseAgentConnectionPollingProps {
|
||||
}
|
||||
|
||||
/**
|
||||
* Polls a cloud integration account until its agent checks in. The timeout is
|
||||
* measured from when polling gets enabled, so re-enabling it starts a fresh window.
|
||||
* Polls a GCP agent account until the agent checks in. The timeout is measured
|
||||
* from when polling gets enabled, so re-enabling it starts a fresh window.
|
||||
*/
|
||||
export function useAgentConnectionPolling({
|
||||
cloudProvider,
|
||||
accountId,
|
||||
enabled,
|
||||
onConnected,
|
||||
@@ -34,7 +33,7 @@ export function useAgentConnectionPolling({
|
||||
}, [enabled]);
|
||||
|
||||
useGetAccount(
|
||||
{ cloudProvider, id: accountId },
|
||||
{ cloudProvider: INTEGRATION_TYPES.GCP, id: accountId },
|
||||
{
|
||||
query: {
|
||||
enabled,
|
||||
@@ -3,8 +3,5 @@
|
||||
}
|
||||
|
||||
.page {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
padding: var(--spacing-4) var(--spacing-6) 0;
|
||||
padding: var(--spacing-4) var(--spacing-6) var(--spacing-6);
|
||||
}
|
||||
|
||||
@@ -3,8 +3,5 @@
|
||||
}
|
||||
|
||||
.page {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
padding: var(--spacing-4) var(--spacing-6) 0;
|
||||
padding: var(--spacing-4) var(--spacing-6) var(--spacing-6);
|
||||
}
|
||||
|
||||
@@ -144,7 +144,7 @@ export const cloudIntegrationMocks = defineStoryMocks({
|
||||
newAccountCheckIn: choiceControl<NewAccountCheckIn>('New account check-in', {
|
||||
group: MUTATIONS,
|
||||
description:
|
||||
'How the poll for the account the connect flow just created answers. `checked-in` connects it on the first poll and the drawer closes with the success toast, `pending` keeps the drawer waiting on the agent with the AWS, Azure or GCP agent setup command up, `error` fails the poll so the drawer reports it could not connect.',
|
||||
'How the poll for the account the connect flow just created answers. `checked-in` connects it on the first poll and the drawer closes with the success toast, `pending` keeps the drawer waiting on the agent (the GCP agent setup command stays up), `error` fails the poll so the drawer reports it could not connect.',
|
||||
options: NEW_ACCOUNT_CHECK_INS,
|
||||
value: 'checked-in',
|
||||
}),
|
||||
@@ -319,7 +319,7 @@ export const connectAwsAccount = async (
|
||||
await screen.findByRole('checkbox', { name: /us-east-1/i }),
|
||||
);
|
||||
await userEvent.click(
|
||||
await screen.findByRole('button', { name: /generate command/i }),
|
||||
await screen.findByRole('button', { name: /launch cloud formation/i }),
|
||||
);
|
||||
};
|
||||
|
||||
@@ -339,7 +339,7 @@ export const connectAzureAccount = async (
|
||||
);
|
||||
await userEvent.type(resourceGroups, 'prod-platform-rg{Enter}');
|
||||
await userEvent.click(
|
||||
await screen.findByRole('button', { name: /generate command/i }),
|
||||
await screen.findByRole('button', { name: /generate azure setup commands/i }),
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -173,8 +173,8 @@ export const TooltipsInDataCollected: Story = {
|
||||
};
|
||||
|
||||
/**
|
||||
* Connecting an AWS account: region and monitored regions picked, the setup
|
||||
* command generated, and the first poll finds the account connected. Set Account
|
||||
* Connecting an AWS account: region and monitored regions picked, the template
|
||||
* launched, and the first poll finds the account connected. Set Account
|
||||
* connection to `error` for the failure toast.
|
||||
*/
|
||||
export const AwsAccountConnectedToast: Story = {
|
||||
@@ -198,7 +198,7 @@ export const AwsAccountConnectionErrorToast: Story = {
|
||||
},
|
||||
};
|
||||
|
||||
/** Connecting an Azure subscription through the generated setup command. */
|
||||
/** Connecting an Azure subscription through the generated setup commands. */
|
||||
export const AzureAccountConnectedToast: Story = {
|
||||
args: { provider: 'azure', accounts: 0 },
|
||||
play: async ({ canvasElement, args }): Promise<void> => {
|
||||
@@ -220,89 +220,6 @@ export const AzureAccountConnectionErrorToast: Story = {
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* The AWS setup command, with the drawer waiting for the account to connect.
|
||||
* Set New account check-in to `checked-in` or `error` to see it connect or fail.
|
||||
*/
|
||||
export const AwsAgentCommand: Story = {
|
||||
args: { accounts: 0, newAccountCheckIn: 'pending' },
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await connectAwsAccount(canvasElement);
|
||||
await screen.findByTestId('aws-agent-command', undefined, untilLoaded);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* The connection poll fails, so the drawer reports it could not connect and
|
||||
* offers Check Again.
|
||||
*/
|
||||
export const AwsAgentConnectionError: Story = {
|
||||
args: { accounts: 0, newAccountCheckIn: 'error' },
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await connectAwsAccount(canvasElement);
|
||||
await screen.findByTestId('aws-check-connection-btn', undefined, untilLoaded);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Leaving the drawer while the agent has not connected yet, which asks first
|
||||
* because closing means starting the installation again.
|
||||
*/
|
||||
export const AwsAgentCloseConfirm: Story = {
|
||||
args: { accounts: 0, newAccountCheckIn: 'pending' },
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await connectAwsAccount(canvasElement);
|
||||
await userEvent.click(
|
||||
await screen.findByTestId('aws-cancel-btn', undefined, untilLoaded),
|
||||
);
|
||||
await screen.findByTestId('aws-close-setup-btn', undefined, untilLoaded);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* The Azure setup command, with the drawer waiting for the subscription to
|
||||
* connect. Set New account check-in to `checked-in` or `error` to see it connect
|
||||
* or fail.
|
||||
*/
|
||||
export const AzureAgentCommand: Story = {
|
||||
args: { provider: 'azure', accounts: 0, newAccountCheckIn: 'pending' },
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await connectAzureAccount(canvasElement);
|
||||
await screen.findByTestId('azure-agent-command', undefined, untilLoaded);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* The connection poll fails, so the drawer reports it could not connect and
|
||||
* offers Check Again.
|
||||
*/
|
||||
export const AzureAgentConnectionError: Story = {
|
||||
args: { provider: 'azure', accounts: 0, newAccountCheckIn: 'error' },
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await connectAzureAccount(canvasElement);
|
||||
await screen.findByTestId(
|
||||
'azure-check-connection-btn',
|
||||
undefined,
|
||||
untilLoaded,
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Leaving the drawer while the agent has not connected yet, which asks first
|
||||
* because closing means starting the installation again.
|
||||
*/
|
||||
export const AzureAgentCloseConfirm: Story = {
|
||||
args: { provider: 'azure', accounts: 0, newAccountCheckIn: 'pending' },
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await connectAzureAccount(canvasElement);
|
||||
await userEvent.click(
|
||||
await screen.findByTestId('azure-cancel-btn', undefined, untilLoaded),
|
||||
);
|
||||
await screen.findByTestId('azure-close-setup-btn', undefined, untilLoaded);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Connecting a GCP account manually: the account is created and the story's
|
||||
* check-in stands in for the agent. A failure at either step shows inline in the
|
||||
|
||||
@@ -366,30 +366,6 @@ export const accountResponse = (
|
||||
};
|
||||
};
|
||||
|
||||
/** The backend's command template, filled in for the story's region. */
|
||||
const AWS_AGENT_COMMAND = {
|
||||
cliCommand: `curl -fsSL 'https://signoz.io/foundry.sh' | bash -s -- cloudintegration aws cloudformation \\
|
||||
--region 'us-east-1' \\
|
||||
--integration-account-id 'aws-account-new' \\
|
||||
--signoz-api-url 'https://story.us.signoz.cloud' \\
|
||||
--signoz-api-key 'story-api-key-8b7d02' \\
|
||||
--ingestion-url 'https://ingest.us.signoz.cloud:443' \\
|
||||
--ingestion-key 'story-ingestion-key-2f9c41' \\
|
||||
--agent-version 'v0.0.8'`,
|
||||
};
|
||||
|
||||
/** The backend's command template, filled in for the story's region. */
|
||||
const AZURE_AGENT_COMMAND = {
|
||||
cliCommand: `curl -fsSL 'https://signoz.io/foundry.sh' | bash -s -- cloudintegration azure bicep \\
|
||||
--region 'australiaeast' \\
|
||||
--integration-account-id 'azure-account-new' \\
|
||||
--signoz-api-url 'https://story.us.signoz.cloud' \\
|
||||
--signoz-api-key 'story-api-key-8b7d02' \\
|
||||
--ingestion-url 'https://ingest.us.signoz.cloud:443' \\
|
||||
--ingestion-key 'story-ingestion-key-2f9c41' \\
|
||||
--agent-version 'v0.0.8'`,
|
||||
};
|
||||
|
||||
/** The backend's command template, filled in for the story's project and region. */
|
||||
const GCP_AGENT_COMMAND = {
|
||||
cliCommand: `curl -fsSL 'https://signoz.io/foundry.sh' | bash -s -- cloudintegration gcp terraform \\
|
||||
@@ -637,8 +613,9 @@ export const credentialsResponse = (): GetConnectionCredentials200 => ({
|
||||
});
|
||||
|
||||
/**
|
||||
* GCP returns its setup command only for an agent connection; a manual one gets
|
||||
* none.
|
||||
* The connection URL is what the setup flow opens in a new tab, which the story
|
||||
* reports through the navigation overlay rather than following. GCP returns its
|
||||
* setup command only for an agent connection; a manual one gets none.
|
||||
*/
|
||||
export const createdAccountResponse = (
|
||||
provider: CloudProvider,
|
||||
@@ -648,8 +625,15 @@ export const createdAccountResponse = (
|
||||
data: {
|
||||
id: newAccountId(provider),
|
||||
connectionArtifact: {
|
||||
aws: AWS_AGENT_COMMAND,
|
||||
azure: AZURE_AGENT_COMMAND,
|
||||
aws: {
|
||||
connectionUrl: `https://console.aws.amazon.com/cloudformation/home#/stacks/create?templateURL=https://signoz.io/${provider}.yaml`,
|
||||
},
|
||||
azure: {
|
||||
cliCommand:
|
||||
'az deployment sub create --template-uri https://signoz.io/azure.json',
|
||||
cloudPowerShellCommand:
|
||||
'New-AzSubscriptionDeployment -TemplateUri https://signoz.io/azure.json',
|
||||
},
|
||||
...(gcpConnectionMethod ===
|
||||
CloudintegrationtypesGCPConnectionMethodDTO.agent && {
|
||||
gcp: GCP_AGENT_COMMAND,
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import { ToggleGroup } from '@signozhq/ui/toggle-group';
|
||||
import { useAppParams } from 'lib/router/useAppParams';
|
||||
|
||||
import { TraceDetailsTab } from '../constants';
|
||||
import { TraceDetailEventKeys, TraceDetailEvents } from '../events';
|
||||
import { useTraceDetailLogEvent } from '../hooks/useTraceDetailLogEvent';
|
||||
import { useTraceDetailsTab } from '../hooks/useTraceDetailsTab';
|
||||
|
||||
import styles from './TraceDetailsHeader.module.scss';
|
||||
@@ -22,15 +19,9 @@ const TAB_ITEMS = [
|
||||
];
|
||||
|
||||
function TraceDetailsTabs(): JSX.Element {
|
||||
const { id: traceId = '' } = useAppParams<'id'>();
|
||||
const [tab, setTab] = useTraceDetailsTab();
|
||||
const logTraceEvent = useTraceDetailLogEvent('v3', traceId);
|
||||
|
||||
const handleChange = (value: string): void => {
|
||||
logTraceEvent(TraceDetailEvents.DetailsTabChanged, {
|
||||
[TraceDetailEventKeys.From]: tab,
|
||||
[TraceDetailEventKeys.To]: value,
|
||||
});
|
||||
// Pushed so the thread's "Go back" returns to the previous tab, not the previous page.
|
||||
void setTab(value as TraceDetailsTab, { history: 'push' });
|
||||
};
|
||||
|
||||
@@ -1,17 +1,12 @@
|
||||
import { getYAxisFormattedValue } from 'components/Graph/yAxisConfig';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import type { SpantypesGettableTraceSummaryDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { NuqsTestingAdapter } from 'nuqs/adapters/testing';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { fireEvent, render, screen, userEvent } from 'tests/test-utils';
|
||||
|
||||
import { TraceDetailsTab } from '../../constants';
|
||||
import { TraceDetailEvents } from '../../events';
|
||||
import TraceDetailsHeader from '../TraceDetailsHeader';
|
||||
import { useTraceSummary } from '../useTraceSummary';
|
||||
|
||||
jest.mock('api/common/logEvent');
|
||||
|
||||
jest.mock('../useTraceSummary', () => ({
|
||||
useTraceSummary: jest.fn(() => ({ data: undefined, isLoading: false })),
|
||||
}));
|
||||
@@ -421,23 +416,4 @@ describe('TraceDetailsHeader – tabs', () => {
|
||||
'false',
|
||||
);
|
||||
});
|
||||
|
||||
it('logs the tab change with the previous and next tab', async () => {
|
||||
const user = userEvent.setup({ delay: null });
|
||||
renderHeader();
|
||||
jest.mocked(logEvent).mockClear();
|
||||
|
||||
await user.click(screen.getByTestId('trace-details-tab-overview'));
|
||||
expect(logEvent).not.toHaveBeenCalled();
|
||||
|
||||
await user.click(screen.getByTestId('trace-details-tab-thread'));
|
||||
|
||||
expect(logEvent).toHaveBeenCalledTimes(1);
|
||||
expect(logEvent).toHaveBeenCalledWith(TraceDetailEvents.DetailsTabChanged, {
|
||||
view: 'v3',
|
||||
traceId: 'trace-123',
|
||||
from: TraceDetailsTab.Overview,
|
||||
to: TraceDetailsTab.Thread,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -27,9 +27,7 @@ import { getUnstableCurrentSearchParams } from 'utils/getUnstableCurrentSearchPa
|
||||
import { ResizableBox } from 'periscope/components/ResizableBox';
|
||||
import { SpanV3 } from 'types/api/trace/getTraceV3';
|
||||
|
||||
import { TraceDetailsTab } from '../constants';
|
||||
import { TraceDetailEventKeys, TraceDetailEvents } from '../events';
|
||||
import { useSpanDetailsOpenedEvent } from '../hooks/useSpanDetailsOpenedEvent';
|
||||
import { useSpanDetailVariant } from '../hooks/useSpanDetailVariant';
|
||||
import { useTraceDetailLogEvent } from '../hooks/useTraceDetailLogEvent';
|
||||
import NoData from '../NoData/NoData';
|
||||
@@ -108,12 +106,6 @@ function TraceDetailsOverview({
|
||||
entityId: selectedSpanId,
|
||||
onClose: handleSpanDetailsClose,
|
||||
});
|
||||
useSpanDetailsOpenedEvent({
|
||||
isOpen: panelState.isOpen,
|
||||
spanId: selectedSpan?.span_id,
|
||||
detailsTab: TraceDetailsTab.Overview,
|
||||
logTraceEvent,
|
||||
});
|
||||
|
||||
const allSpansRef = useRef<SpanV3[]>([]);
|
||||
const deepLinkResolvedRef = useRef(false);
|
||||
@@ -207,7 +199,6 @@ function TraceDetailsOverview({
|
||||
dataLoadedFiredForRef.current = traceId;
|
||||
const numServices = new Set(payload.spans.map((s) => s['service.name'])).size;
|
||||
logTraceEvent(TraceDetailEvents.DataLoaded, {
|
||||
[TraceDetailEventKeys.DetailsTab]: TraceDetailsTab.Overview,
|
||||
[TraceDetailEventKeys.TotalSpansCount]: totalSpansCount,
|
||||
[TraceDetailEventKeys.NumServices]: numServices,
|
||||
[TraceDetailEventKeys.TraceDurationMs]:
|
||||
|
||||
@@ -1,15 +1,11 @@
|
||||
import { MutableRefObject } from 'react';
|
||||
import { Callout } from '@signozhq/ui/callout';
|
||||
import { back, hasInAppHistory } from 'lib/router/navigation';
|
||||
import { useAppParams } from 'lib/router/useAppParams';
|
||||
|
||||
import { TraceDetailsTab } from '../constants';
|
||||
import { useSpanDetailsOpenedEvent } from '../hooks/useSpanDetailsOpenedEvent';
|
||||
import { useSpanDetailVariant } from '../hooks/useSpanDetailVariant';
|
||||
import { useTraceDetailLogEvent } from '../hooks/useTraceDetailLogEvent';
|
||||
import { useTraceDetailsTab } from '../hooks/useTraceDetailsTab';
|
||||
import { SpanDetailVariant } from '../SpanDetailsPanel/constants';
|
||||
import { useThreadDataLoadedEvent } from './hooks/useThreadDataLoadedEvent';
|
||||
import { useThreadSpanSelection } from './hooks/useThreadSpanSelection';
|
||||
import { useThreadView } from './hooks/useThreadView';
|
||||
import { useTraceThread } from './hooks/useTraceThread';
|
||||
@@ -27,14 +23,7 @@ import styles from './TraceDetailsThread.module.scss';
|
||||
|
||||
const INITIAL_LOADER_COUNT = 4;
|
||||
|
||||
interface TraceDetailsThreadProps {
|
||||
// Owned by the page so the load event fires once per trace, not per tab visit.
|
||||
dataLoadedFiredForRef: MutableRefObject<string>;
|
||||
}
|
||||
|
||||
function TraceDetailsThread({
|
||||
dataLoadedFiredForRef,
|
||||
}: TraceDetailsThreadProps): JSX.Element {
|
||||
function TraceDetailsThread(): JSX.Element {
|
||||
const { id: traceId } = useAppParams<'id'>();
|
||||
const [, setTab] = useTraceDetailsTab();
|
||||
const [view, setView] = useThreadView();
|
||||
@@ -73,21 +62,6 @@ function TraceDetailsThread({
|
||||
const [spanDetailVariant, setSpanDetailVariant] = useSpanDetailVariant();
|
||||
const isBottomDocked = spanDetailVariant === SpanDetailVariant.DOCKED;
|
||||
|
||||
const logTraceEvent = useTraceDetailLogEvent('v3', traceId || '');
|
||||
useThreadDataLoadedEvent({
|
||||
traceId: traceId || '',
|
||||
hasSpans: spans.length > 0,
|
||||
spanPanelVariant: spanDetailVariant,
|
||||
firedForRef: dataLoadedFiredForRef,
|
||||
logTraceEvent,
|
||||
});
|
||||
useSpanDetailsOpenedEvent({
|
||||
isOpen: panelState.isOpen,
|
||||
spanId: selectedSpan?.span_id,
|
||||
detailsTab: TraceDetailsTab.Thread,
|
||||
logTraceEvent,
|
||||
});
|
||||
|
||||
const spanDetails = panelState.isOpen && selectedSpan && (
|
||||
<ThreadSpanDetails
|
||||
panelState={panelState}
|
||||
|
||||
@@ -1,174 +0,0 @@
|
||||
import { MutableRefObject, ReactNode } from 'react';
|
||||
import { QueryClient, QueryClientProvider } from 'react-query';
|
||||
import {
|
||||
GetTraceSummary200,
|
||||
SpantypesGettableTraceSummaryDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { getGetTraceSummaryQueryKey } from 'api/generated/services/tracedetail';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { renderHook, waitFor } from 'tests/test-utils';
|
||||
|
||||
import { TraceDetailsTab } from '../../../constants';
|
||||
import { TraceDetailEvents } from '../../../events';
|
||||
import { TraceDetailLogEvent } from '../../../hooks/useTraceDetailLogEvent';
|
||||
import { SpanDetailVariant } from '../../../SpanDetailsPanel/constants';
|
||||
import { useThreadDataLoadedEvent } from '../useThreadDataLoadedEvent';
|
||||
|
||||
const SUMMARIES: Record<string, SpantypesGettableTraceSummaryDTO> = {
|
||||
'trace-a': {
|
||||
startTimestampMillis: 1_000,
|
||||
endTimestampMillis: 4_000,
|
||||
totalSpansCount: 12,
|
||||
totalErrorSpansCount: 2,
|
||||
hasMissingSpans: false,
|
||||
rootServiceEntryPoint: 'POST /chat',
|
||||
rootServiceName: 'agent',
|
||||
rootSpanStatusCode: 'STATUS_CODE_ERROR',
|
||||
},
|
||||
'trace-b': {
|
||||
startTimestampMillis: 5_000,
|
||||
endTimestampMillis: 5_500,
|
||||
totalSpansCount: 3,
|
||||
totalErrorSpansCount: 0,
|
||||
hasMissingSpans: false,
|
||||
rootServiceEntryPoint: 'POST /chat',
|
||||
rootServiceName: 'agent',
|
||||
rootSpanStatusCode: 'STATUS_CODE_OK',
|
||||
},
|
||||
};
|
||||
|
||||
interface HookProps {
|
||||
traceId: string;
|
||||
hasSpans: boolean;
|
||||
spanPanelVariant?: SpanDetailVariant;
|
||||
}
|
||||
|
||||
function renderDataLoadedEvent(
|
||||
initialProps: HookProps,
|
||||
firedForRef: MutableRefObject<string> = { current: '' },
|
||||
): {
|
||||
logTraceEvent: jest.MockedFunction<TraceDetailLogEvent>;
|
||||
rerender: (props: HookProps) => void;
|
||||
queryClient: QueryClient;
|
||||
} {
|
||||
const logTraceEvent = jest.fn() as jest.MockedFunction<TraceDetailLogEvent>;
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
});
|
||||
const wrapper = ({ children }: { children: ReactNode }): JSX.Element => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
);
|
||||
const { rerender } = renderHook(
|
||||
({ traceId, hasSpans, spanPanelVariant }: HookProps) =>
|
||||
useThreadDataLoadedEvent({
|
||||
traceId,
|
||||
hasSpans,
|
||||
spanPanelVariant: spanPanelVariant ?? SpanDetailVariant.DOCKED_RIGHT,
|
||||
firedForRef,
|
||||
logTraceEvent,
|
||||
}),
|
||||
{ initialProps, wrapper },
|
||||
);
|
||||
return { logTraceEvent, rerender, queryClient };
|
||||
}
|
||||
|
||||
describe('useThreadDataLoadedEvent', () => {
|
||||
beforeEach(() => {
|
||||
server.use(
|
||||
rest.get('*/api/v1/traces/:traceId/summary', (req, res, ctx) => {
|
||||
const body: GetTraceSummary200 = {
|
||||
status: 'success',
|
||||
data: SUMMARIES[req.params.traceId as string],
|
||||
};
|
||||
return res(ctx.status(200), ctx.json(body));
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('waits for the trace summary, then reports it as a thread load', async () => {
|
||||
const { logTraceEvent } = renderDataLoadedEvent({
|
||||
traceId: 'trace-a',
|
||||
hasSpans: true,
|
||||
});
|
||||
|
||||
expect(logTraceEvent).not.toHaveBeenCalled();
|
||||
|
||||
await waitFor(() => expect(logTraceEvent).toHaveBeenCalledTimes(1));
|
||||
expect(logTraceEvent).toHaveBeenCalledWith(TraceDetailEvents.DataLoaded, {
|
||||
detailsTab: TraceDetailsTab.Thread,
|
||||
totalSpansCount: 12,
|
||||
traceDurationMs: 3_000,
|
||||
hadErrors: true,
|
||||
spanPanelVariant: SpanDetailVariant.DOCKED_RIGHT,
|
||||
});
|
||||
});
|
||||
|
||||
it('waits for the thread spans even when the summary is already loaded', async () => {
|
||||
const { logTraceEvent, rerender, queryClient } = renderDataLoadedEvent({
|
||||
traceId: 'trace-a',
|
||||
hasSpans: false,
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
queryClient.getQueryData(
|
||||
getGetTraceSummaryQueryKey({ traceID: 'trace-a' }),
|
||||
),
|
||||
).toBeDefined(),
|
||||
);
|
||||
rerender({ traceId: 'trace-a', hasSpans: false });
|
||||
|
||||
expect(logTraceEvent).not.toHaveBeenCalled();
|
||||
|
||||
rerender({ traceId: 'trace-a', hasSpans: true });
|
||||
|
||||
expect(logTraceEvent).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('reports a trace once, including when the tab is visited again', async () => {
|
||||
const firedForRef = { current: '' };
|
||||
const firstVisit = renderDataLoadedEvent(
|
||||
{ traceId: 'trace-a', hasSpans: true },
|
||||
firedForRef,
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(firstVisit.logTraceEvent).toHaveBeenCalledTimes(1),
|
||||
);
|
||||
firstVisit.rerender({
|
||||
traceId: 'trace-a',
|
||||
hasSpans: true,
|
||||
spanPanelVariant: SpanDetailVariant.DOCKED,
|
||||
});
|
||||
|
||||
const secondVisit = renderDataLoadedEvent(
|
||||
{ traceId: 'trace-a', hasSpans: true },
|
||||
firedForRef,
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
secondVisit.queryClient.getQueryData(
|
||||
getGetTraceSummaryQueryKey({ traceID: 'trace-a' }),
|
||||
),
|
||||
).toBeDefined(),
|
||||
);
|
||||
secondVisit.rerender({ traceId: 'trace-a', hasSpans: true });
|
||||
|
||||
expect(firstVisit.logTraceEvent).toHaveBeenCalledTimes(1);
|
||||
expect(secondVisit.logTraceEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reports the next trace with its own summary', async () => {
|
||||
const { logTraceEvent, rerender } = renderDataLoadedEvent({
|
||||
traceId: 'trace-a',
|
||||
hasSpans: true,
|
||||
});
|
||||
await waitFor(() => expect(logTraceEvent).toHaveBeenCalledTimes(1));
|
||||
|
||||
rerender({ traceId: 'trace-b', hasSpans: true });
|
||||
|
||||
await waitFor(() => expect(logTraceEvent).toHaveBeenCalledTimes(2));
|
||||
expect(logTraceEvent).toHaveBeenLastCalledWith(
|
||||
TraceDetailEvents.DataLoaded,
|
||||
expect.objectContaining({ totalSpansCount: 3, traceDurationMs: 500 }),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,45 +0,0 @@
|
||||
import { MutableRefObject, useEffect } from 'react';
|
||||
import { useGetTraceSummary } from 'api/generated/services/tracedetail';
|
||||
|
||||
import { TraceDetailsTab } from '../../constants';
|
||||
import { TraceDetailEventKeys, TraceDetailEvents } from '../../events';
|
||||
import { TraceDetailLogEvent } from '../../hooks/useTraceDetailLogEvent';
|
||||
import { SpanDetailVariant } from '../../SpanDetailsPanel/constants';
|
||||
|
||||
interface ThreadDataLoadedEventArgs {
|
||||
traceId: string;
|
||||
hasSpans: boolean;
|
||||
spanPanelVariant: SpanDetailVariant;
|
||||
firedForRef: MutableRefObject<string>;
|
||||
logTraceEvent: TraceDetailLogEvent;
|
||||
}
|
||||
|
||||
export function useThreadDataLoadedEvent({
|
||||
traceId,
|
||||
hasSpans,
|
||||
spanPanelVariant,
|
||||
firedForRef,
|
||||
logTraceEvent,
|
||||
}: ThreadDataLoadedEventArgs): void {
|
||||
// No keepPreviousData: a previous trace's summary must not be reported for this one.
|
||||
const { data } = useGetTraceSummary(
|
||||
{ traceID: traceId },
|
||||
{ query: { enabled: !!traceId, refetchOnMount: false } },
|
||||
);
|
||||
const summary = data?.data;
|
||||
|
||||
useEffect(() => {
|
||||
if (!traceId || firedForRef.current === traceId || !hasSpans || !summary) {
|
||||
return;
|
||||
}
|
||||
firedForRef.current = traceId;
|
||||
logTraceEvent(TraceDetailEvents.DataLoaded, {
|
||||
[TraceDetailEventKeys.DetailsTab]: TraceDetailsTab.Thread,
|
||||
[TraceDetailEventKeys.TotalSpansCount]: summary.totalSpansCount,
|
||||
[TraceDetailEventKeys.TraceDurationMs]:
|
||||
summary.endTimestampMillis - summary.startTimestampMillis,
|
||||
[TraceDetailEventKeys.HadErrors]: summary.totalErrorSpansCount > 0,
|
||||
[TraceDetailEventKeys.SpanPanelVariant]: spanPanelVariant,
|
||||
});
|
||||
}, [traceId, hasSpans, summary, spanPanelVariant, firedForRef, logTraceEvent]);
|
||||
}
|
||||
@@ -12,8 +12,6 @@ export enum TraceDetailEvents {
|
||||
SpanPercentileTimeRangeChanged = 'Trace Detail: Span percentile time range changed',
|
||||
SpanPercentileAttributesSelectorToggled = 'Trace Detail: Span percentile attributes selector toggled',
|
||||
SpanPercentileAttributeChanged = 'Trace Detail: Span percentile attribute changed',
|
||||
SpanDetailsOpened = 'Trace Detail: Span details opened',
|
||||
DetailsTabChanged = 'Trace Detail: Details tab changed',
|
||||
}
|
||||
|
||||
export enum TraceDetailEventKeys {
|
||||
@@ -30,7 +28,7 @@ export enum TraceDetailEventKeys {
|
||||
SpanPanelVariant = 'spanPanelVariant',
|
||||
ColorByField = 'colorByField',
|
||||
PreviewFieldsCount = 'previewFieldsCount',
|
||||
// View switched / details tab changed
|
||||
// View switched
|
||||
From = 'from',
|
||||
To = 'to',
|
||||
DwellMs = 'dwellMs',
|
||||
@@ -46,8 +44,6 @@ export enum TraceDetailEventKeys {
|
||||
PercentileValue = 'percentileValue',
|
||||
ResourceAttributeKey = 'resourceAttributeKey',
|
||||
Selected = 'selected',
|
||||
// Data loaded / span details opened: which tab the user is on
|
||||
DetailsTab = 'detailsTab',
|
||||
}
|
||||
|
||||
export type TraceDetailView = 'v2' | 'v3';
|
||||
|
||||
@@ -1,90 +0,0 @@
|
||||
import { renderHook } from 'tests/test-utils';
|
||||
|
||||
import { TraceDetailsTab } from '../../constants';
|
||||
import { TraceDetailEvents } from '../../events';
|
||||
import { useSpanDetailsOpenedEvent } from '../useSpanDetailsOpenedEvent';
|
||||
import { TraceDetailLogEvent } from '../useTraceDetailLogEvent';
|
||||
|
||||
interface PanelProps {
|
||||
isOpen: boolean;
|
||||
spanId?: string;
|
||||
}
|
||||
|
||||
function renderOpenedEvent(initialProps: PanelProps): {
|
||||
logTraceEvent: jest.MockedFunction<TraceDetailLogEvent>;
|
||||
rerender: (props: PanelProps) => void;
|
||||
} {
|
||||
const logTraceEvent = jest.fn() as jest.MockedFunction<TraceDetailLogEvent>;
|
||||
const { rerender } = renderHook(
|
||||
({ isOpen, spanId }: PanelProps) =>
|
||||
useSpanDetailsOpenedEvent({
|
||||
isOpen,
|
||||
spanId,
|
||||
detailsTab: TraceDetailsTab.Thread,
|
||||
logTraceEvent,
|
||||
}),
|
||||
{ initialProps },
|
||||
);
|
||||
return { logTraceEvent, rerender };
|
||||
}
|
||||
|
||||
function openedSpanIds(
|
||||
logTraceEvent: jest.MockedFunction<TraceDetailLogEvent>,
|
||||
): unknown[] {
|
||||
return logTraceEvent.mock.calls.map(([, attributes]) => attributes?.spanId);
|
||||
}
|
||||
|
||||
describe('useSpanDetailsOpenedEvent', () => {
|
||||
it('waits for the panel to be open on a span, then reports it with the tab', () => {
|
||||
const { logTraceEvent, rerender } = renderOpenedEvent({ isOpen: false });
|
||||
rerender({ isOpen: true });
|
||||
rerender({ isOpen: false, spanId: 'span-1' });
|
||||
|
||||
expect(logTraceEvent).not.toHaveBeenCalled();
|
||||
|
||||
rerender({ isOpen: true, spanId: 'span-1' });
|
||||
|
||||
expect(logTraceEvent).toHaveBeenCalledTimes(1);
|
||||
expect(logTraceEvent).toHaveBeenCalledWith(
|
||||
TraceDetailEvents.SpanDetailsOpened,
|
||||
{ spanId: 'span-1', detailsTab: TraceDetailsTab.Thread },
|
||||
);
|
||||
});
|
||||
|
||||
it('does not repeat while the same span stays open', () => {
|
||||
const { logTraceEvent, rerender } = renderOpenedEvent({
|
||||
isOpen: true,
|
||||
spanId: 'span-1',
|
||||
});
|
||||
rerender({ isOpen: true, spanId: 'span-1' });
|
||||
rerender({ isOpen: true, spanId: 'span-1' });
|
||||
|
||||
expect(logTraceEvent).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('reports the same span again after the panel is closed and reopened', () => {
|
||||
const { logTraceEvent, rerender } = renderOpenedEvent({
|
||||
isOpen: true,
|
||||
spanId: 'span-1',
|
||||
});
|
||||
rerender({ isOpen: false });
|
||||
rerender({ isOpen: true, spanId: 'span-1' });
|
||||
|
||||
expect(openedSpanIds(logTraceEvent)).toStrictEqual(['span-1', 'span-1']);
|
||||
});
|
||||
|
||||
it('reports each span selected while the panel stays open', () => {
|
||||
const { logTraceEvent, rerender } = renderOpenedEvent({
|
||||
isOpen: true,
|
||||
spanId: 'span-1',
|
||||
});
|
||||
rerender({ isOpen: true, spanId: 'span-2' });
|
||||
rerender({ isOpen: true, spanId: 'span-3' });
|
||||
|
||||
expect(openedSpanIds(logTraceEvent)).toStrictEqual([
|
||||
'span-1',
|
||||
'span-2',
|
||||
'span-3',
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,30 +0,0 @@
|
||||
import { useEffect } from 'react';
|
||||
|
||||
import { TraceDetailsTab } from '../constants';
|
||||
import { TraceDetailEventKeys, TraceDetailEvents } from '../events';
|
||||
import { TraceDetailLogEvent } from './useTraceDetailLogEvent';
|
||||
|
||||
interface SpanDetailsOpenedEventArgs {
|
||||
isOpen: boolean;
|
||||
spanId: string | undefined;
|
||||
detailsTab: TraceDetailsTab;
|
||||
logTraceEvent: TraceDetailLogEvent;
|
||||
}
|
||||
|
||||
// Fires once per span shown in the details panel; resets when the panel closes.
|
||||
export function useSpanDetailsOpenedEvent({
|
||||
isOpen,
|
||||
spanId,
|
||||
detailsTab,
|
||||
logTraceEvent,
|
||||
}: SpanDetailsOpenedEventArgs): void {
|
||||
useEffect(() => {
|
||||
if (!isOpen || !spanId) {
|
||||
return;
|
||||
}
|
||||
logTraceEvent(TraceDetailEvents.SpanDetailsOpened, {
|
||||
[TraceDetailEventKeys.SpanId]: spanId,
|
||||
[TraceDetailEventKeys.DetailsTab]: detailsTab,
|
||||
});
|
||||
}, [isOpen, spanId, detailsTab, logTraceEvent]);
|
||||
}
|
||||
@@ -16,7 +16,6 @@ function TraceDetailsV3(): JSX.Element {
|
||||
// Tracks which traceId the load event already fired for, so navigating
|
||||
// between traces (the route component stays mounted) re-fires it once each.
|
||||
const dataLoadedFiredForRef = useRef<string>('');
|
||||
const threadDataLoadedFiredForRef = useRef<string>('');
|
||||
|
||||
const handleFilteredSpansChange = useCallback(
|
||||
(spanIds: string[], isActive: boolean): void => {
|
||||
@@ -40,7 +39,7 @@ function TraceDetailsV3(): JSX.Element {
|
||||
dataLoadedFiredForRef={dataLoadedFiredForRef}
|
||||
/>
|
||||
) : (
|
||||
<TraceDetailsThread dataLoadedFiredForRef={threadDataLoadedFiredForRef} />
|
||||
<TraceDetailsThread />
|
||||
)}
|
||||
</TraceDetailsWrapper>
|
||||
);
|
||||
|
||||
103
grammar/AggregationExpression.g4
Normal file
103
grammar/AggregationExpression.g4
Normal file
@@ -0,0 +1,103 @@
|
||||
grammar AggregationExpression;
|
||||
|
||||
/*
|
||||
* Parser Rules
|
||||
*/
|
||||
|
||||
// Expressions after the first are ignored, as the rewriter always has.
|
||||
query
|
||||
: expression ( COMMA expression )* EOF
|
||||
;
|
||||
|
||||
/*
|
||||
* Aggregation calls combined with arithmetic. Earlier alternatives bind tighter.
|
||||
* E.g.: count(), p99(duration_nano), sum(a) + sum(b), count() / 60, -(sum(a) - sum(b))
|
||||
*/
|
||||
expression
|
||||
: (PLUS | MINUS) expression # unaryExpression
|
||||
| expression (STAR | SLASH | PERCENT) expression # multiplicativeExpression
|
||||
| expression (PLUS | MINUS) expression # additiveExpression
|
||||
| LPAREN expression RPAREN # parenthesizedExpression
|
||||
| functionCall # functionExpression
|
||||
| NUMBER # numberExpression
|
||||
;
|
||||
|
||||
/*
|
||||
* E.g.: count(), sum(bytes), count_distinct(a, b), countIf(level = 'error'),
|
||||
* sumIf(bytes, status IN (500, 503))
|
||||
*/
|
||||
functionCall
|
||||
: KEY LPAREN argumentList? RPAREN
|
||||
;
|
||||
|
||||
argumentList
|
||||
: argument ( COMMA argument )*
|
||||
;
|
||||
|
||||
/*
|
||||
* An argument is a field key, or for a *If combinator a filter predicate, which
|
||||
* the filter grammar validates. Commas separate arguments only at the top level.
|
||||
*/
|
||||
argument
|
||||
: argumentToken+
|
||||
;
|
||||
|
||||
argumentToken
|
||||
: KEY
|
||||
| NUMBER
|
||||
| QUOTED_TEXT
|
||||
| OPERATOR
|
||||
| PLUS | MINUS | STAR | SLASH | PERCENT
|
||||
| LPAREN ( argumentToken | COMMA )* RPAREN
|
||||
| LBRACK ( argumentToken | COMMA )* RBRACK
|
||||
| OTHER
|
||||
;
|
||||
|
||||
/*
|
||||
* Lexer Rules
|
||||
*/
|
||||
|
||||
LPAREN : '(' ;
|
||||
RPAREN : ')' ;
|
||||
LBRACK : '[' ;
|
||||
RBRACK : ']' ;
|
||||
COMMA : ',' ;
|
||||
|
||||
PLUS : '+' ;
|
||||
MINUS : '-' ;
|
||||
STAR : '*' ;
|
||||
SLASH : '/' ;
|
||||
PERCENT : '%' ;
|
||||
|
||||
OPERATOR
|
||||
: '=' | '==' | '!=' | '<>' | '<' | '<=' | '>' | '>='
|
||||
;
|
||||
|
||||
// No leading sign, so `count()-10` reads as a subtraction.
|
||||
NUMBER
|
||||
: DIGIT+ ('.' DIGIT*)? ([eE] [+-]? DIGIT+)?
|
||||
| '.' DIGIT+ ([eE] [+-]? DIGIT+)?
|
||||
;
|
||||
|
||||
QUOTED_TEXT
|
||||
: '"' ( ~["\\] | '\\' . )* '"'
|
||||
| '\'' ( ~['\\] | '\\' . )* '\''
|
||||
;
|
||||
|
||||
// Same key syntax as the filter grammar.
|
||||
fragment SEGMENT : [a-zA-Z$_@{#] [a-zA-Z0-9$_@#{}:\-/]* ;
|
||||
fragment EMPTY_BRACKS : '[' ']' ;
|
||||
fragment OLD_JSON_BRACKS : '[' '*' ']' ;
|
||||
|
||||
KEY
|
||||
: SEGMENT ( '.' SEGMENT | EMPTY_BRACKS | OLD_JSON_BRACKS | '.' DIGIT+ )*
|
||||
;
|
||||
|
||||
WS
|
||||
: [ \t\r\n]+ -> skip
|
||||
;
|
||||
|
||||
fragment DIGIT : [0-9] ;
|
||||
|
||||
// Anything else is left for a predicate's own grammar to judge.
|
||||
OTHER : . ;
|
||||
@@ -0,0 +1,49 @@
|
||||
token literal names:
|
||||
null
|
||||
'('
|
||||
')'
|
||||
'['
|
||||
']'
|
||||
','
|
||||
'+'
|
||||
'-'
|
||||
'*'
|
||||
'/'
|
||||
'%'
|
||||
null
|
||||
null
|
||||
null
|
||||
null
|
||||
null
|
||||
null
|
||||
|
||||
token symbolic names:
|
||||
null
|
||||
LPAREN
|
||||
RPAREN
|
||||
LBRACK
|
||||
RBRACK
|
||||
COMMA
|
||||
PLUS
|
||||
MINUS
|
||||
STAR
|
||||
SLASH
|
||||
PERCENT
|
||||
OPERATOR
|
||||
NUMBER
|
||||
QUOTED_TEXT
|
||||
KEY
|
||||
WS
|
||||
OTHER
|
||||
|
||||
rule names:
|
||||
query
|
||||
expression
|
||||
functionCall
|
||||
argumentList
|
||||
argument
|
||||
argumentToken
|
||||
|
||||
|
||||
atn:
|
||||
[4, 1, 16, 95, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 1, 0, 1, 0, 1, 0, 5, 0, 16, 8, 0, 10, 0, 12, 0, 19, 9, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 32, 8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 1, 40, 8, 1, 10, 1, 12, 1, 43, 9, 1, 1, 2, 1, 2, 1, 2, 3, 2, 48, 8, 2, 1, 2, 1, 2, 1, 3, 1, 3, 1, 3, 5, 3, 55, 8, 3, 10, 3, 12, 3, 58, 9, 3, 1, 4, 4, 4, 61, 8, 4, 11, 4, 12, 4, 62, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 5, 5, 77, 8, 5, 10, 5, 12, 5, 80, 9, 5, 1, 5, 1, 5, 1, 5, 1, 5, 5, 5, 86, 8, 5, 10, 5, 12, 5, 89, 9, 5, 1, 5, 1, 5, 3, 5, 93, 8, 5, 1, 5, 0, 1, 2, 6, 0, 2, 4, 6, 8, 10, 0, 2, 1, 0, 6, 7, 1, 0, 8, 10, 112, 0, 12, 1, 0, 0, 0, 2, 31, 1, 0, 0, 0, 4, 44, 1, 0, 0, 0, 6, 51, 1, 0, 0, 0, 8, 60, 1, 0, 0, 0, 10, 92, 1, 0, 0, 0, 12, 17, 3, 2, 1, 0, 13, 14, 5, 5, 0, 0, 14, 16, 3, 2, 1, 0, 15, 13, 1, 0, 0, 0, 16, 19, 1, 0, 0, 0, 17, 15, 1, 0, 0, 0, 17, 18, 1, 0, 0, 0, 18, 20, 1, 0, 0, 0, 19, 17, 1, 0, 0, 0, 20, 21, 5, 0, 0, 1, 21, 1, 1, 0, 0, 0, 22, 23, 6, 1, -1, 0, 23, 24, 7, 0, 0, 0, 24, 32, 3, 2, 1, 6, 25, 26, 5, 1, 0, 0, 26, 27, 3, 2, 1, 0, 27, 28, 5, 2, 0, 0, 28, 32, 1, 0, 0, 0, 29, 32, 3, 4, 2, 0, 30, 32, 5, 12, 0, 0, 31, 22, 1, 0, 0, 0, 31, 25, 1, 0, 0, 0, 31, 29, 1, 0, 0, 0, 31, 30, 1, 0, 0, 0, 32, 41, 1, 0, 0, 0, 33, 34, 10, 5, 0, 0, 34, 35, 7, 1, 0, 0, 35, 40, 3, 2, 1, 6, 36, 37, 10, 4, 0, 0, 37, 38, 7, 0, 0, 0, 38, 40, 3, 2, 1, 5, 39, 33, 1, 0, 0, 0, 39, 36, 1, 0, 0, 0, 40, 43, 1, 0, 0, 0, 41, 39, 1, 0, 0, 0, 41, 42, 1, 0, 0, 0, 42, 3, 1, 0, 0, 0, 43, 41, 1, 0, 0, 0, 44, 45, 5, 14, 0, 0, 45, 47, 5, 1, 0, 0, 46, 48, 3, 6, 3, 0, 47, 46, 1, 0, 0, 0, 47, 48, 1, 0, 0, 0, 48, 49, 1, 0, 0, 0, 49, 50, 5, 2, 0, 0, 50, 5, 1, 0, 0, 0, 51, 56, 3, 8, 4, 0, 52, 53, 5, 5, 0, 0, 53, 55, 3, 8, 4, 0, 54, 52, 1, 0, 0, 0, 55, 58, 1, 0, 0, 0, 56, 54, 1, 0, 0, 0, 56, 57, 1, 0, 0, 0, 57, 7, 1, 0, 0, 0, 58, 56, 1, 0, 0, 0, 59, 61, 3, 10, 5, 0, 60, 59, 1, 0, 0, 0, 61, 62, 1, 0, 0, 0, 62, 60, 1, 0, 0, 0, 62, 63, 1, 0, 0, 0, 63, 9, 1, 0, 0, 0, 64, 93, 5, 14, 0, 0, 65, 93, 5, 12, 0, 0, 66, 93, 5, 13, 0, 0, 67, 93, 5, 11, 0, 0, 68, 93, 5, 6, 0, 0, 69, 93, 5, 7, 0, 0, 70, 93, 5, 8, 0, 0, 71, 93, 5, 9, 0, 0, 72, 93, 5, 10, 0, 0, 73, 78, 5, 1, 0, 0, 74, 77, 3, 10, 5, 0, 75, 77, 5, 5, 0, 0, 76, 74, 1, 0, 0, 0, 76, 75, 1, 0, 0, 0, 77, 80, 1, 0, 0, 0, 78, 76, 1, 0, 0, 0, 78, 79, 1, 0, 0, 0, 79, 81, 1, 0, 0, 0, 80, 78, 1, 0, 0, 0, 81, 93, 5, 2, 0, 0, 82, 87, 5, 3, 0, 0, 83, 86, 3, 10, 5, 0, 84, 86, 5, 5, 0, 0, 85, 83, 1, 0, 0, 0, 85, 84, 1, 0, 0, 0, 86, 89, 1, 0, 0, 0, 87, 85, 1, 0, 0, 0, 87, 88, 1, 0, 0, 0, 88, 90, 1, 0, 0, 0, 89, 87, 1, 0, 0, 0, 90, 93, 5, 4, 0, 0, 91, 93, 5, 16, 0, 0, 92, 64, 1, 0, 0, 0, 92, 65, 1, 0, 0, 0, 92, 66, 1, 0, 0, 0, 92, 67, 1, 0, 0, 0, 92, 68, 1, 0, 0, 0, 92, 69, 1, 0, 0, 0, 92, 70, 1, 0, 0, 0, 92, 71, 1, 0, 0, 0, 92, 72, 1, 0, 0, 0, 92, 73, 1, 0, 0, 0, 92, 82, 1, 0, 0, 0, 92, 91, 1, 0, 0, 0, 93, 11, 1, 0, 0, 0, 12, 17, 31, 39, 41, 47, 56, 62, 76, 78, 85, 87, 92]
|
||||
@@ -0,0 +1,26 @@
|
||||
LPAREN=1
|
||||
RPAREN=2
|
||||
LBRACK=3
|
||||
RBRACK=4
|
||||
COMMA=5
|
||||
PLUS=6
|
||||
MINUS=7
|
||||
STAR=8
|
||||
SLASH=9
|
||||
PERCENT=10
|
||||
OPERATOR=11
|
||||
NUMBER=12
|
||||
QUOTED_TEXT=13
|
||||
KEY=14
|
||||
WS=15
|
||||
OTHER=16
|
||||
'('=1
|
||||
')'=2
|
||||
'['=3
|
||||
']'=4
|
||||
','=5
|
||||
'+'=6
|
||||
'-'=7
|
||||
'*'=8
|
||||
'/'=9
|
||||
'%'=10
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,26 @@
|
||||
LPAREN=1
|
||||
RPAREN=2
|
||||
LBRACK=3
|
||||
RBRACK=4
|
||||
COMMA=5
|
||||
PLUS=6
|
||||
MINUS=7
|
||||
STAR=8
|
||||
SLASH=9
|
||||
PERCENT=10
|
||||
OPERATOR=11
|
||||
NUMBER=12
|
||||
QUOTED_TEXT=13
|
||||
KEY=14
|
||||
WS=15
|
||||
OTHER=16
|
||||
'('=1
|
||||
')'=2
|
||||
'['=3
|
||||
']'=4
|
||||
','=5
|
||||
'+'=6
|
||||
'-'=7
|
||||
'*'=8
|
||||
'/'=9
|
||||
'%'=10
|
||||
@@ -0,0 +1,92 @@
|
||||
// Code generated from grammar/AggregationExpression.g4 by ANTLR 4.13.2. DO NOT EDIT.
|
||||
|
||||
package parser // AggregationExpression
|
||||
|
||||
import "github.com/antlr4-go/antlr/v4"
|
||||
|
||||
// BaseAggregationExpressionListener is a complete listener for a parse tree produced by AggregationExpressionParser.
|
||||
type BaseAggregationExpressionListener struct{}
|
||||
|
||||
var _ AggregationExpressionListener = &BaseAggregationExpressionListener{}
|
||||
|
||||
// VisitTerminal is called when a terminal node is visited.
|
||||
func (s *BaseAggregationExpressionListener) VisitTerminal(node antlr.TerminalNode) {}
|
||||
|
||||
// VisitErrorNode is called when an error node is visited.
|
||||
func (s *BaseAggregationExpressionListener) VisitErrorNode(node antlr.ErrorNode) {}
|
||||
|
||||
// EnterEveryRule is called when any rule is entered.
|
||||
func (s *BaseAggregationExpressionListener) EnterEveryRule(ctx antlr.ParserRuleContext) {}
|
||||
|
||||
// ExitEveryRule is called when any rule is exited.
|
||||
func (s *BaseAggregationExpressionListener) ExitEveryRule(ctx antlr.ParserRuleContext) {}
|
||||
|
||||
// EnterQuery is called when production query is entered.
|
||||
func (s *BaseAggregationExpressionListener) EnterQuery(ctx *QueryContext) {}
|
||||
|
||||
// ExitQuery is called when production query is exited.
|
||||
func (s *BaseAggregationExpressionListener) ExitQuery(ctx *QueryContext) {}
|
||||
|
||||
// EnterParenthesizedExpression is called when production parenthesizedExpression is entered.
|
||||
func (s *BaseAggregationExpressionListener) EnterParenthesizedExpression(ctx *ParenthesizedExpressionContext) {
|
||||
}
|
||||
|
||||
// ExitParenthesizedExpression is called when production parenthesizedExpression is exited.
|
||||
func (s *BaseAggregationExpressionListener) ExitParenthesizedExpression(ctx *ParenthesizedExpressionContext) {
|
||||
}
|
||||
|
||||
// EnterAdditiveExpression is called when production additiveExpression is entered.
|
||||
func (s *BaseAggregationExpressionListener) EnterAdditiveExpression(ctx *AdditiveExpressionContext) {}
|
||||
|
||||
// ExitAdditiveExpression is called when production additiveExpression is exited.
|
||||
func (s *BaseAggregationExpressionListener) ExitAdditiveExpression(ctx *AdditiveExpressionContext) {}
|
||||
|
||||
// EnterNumberExpression is called when production numberExpression is entered.
|
||||
func (s *BaseAggregationExpressionListener) EnterNumberExpression(ctx *NumberExpressionContext) {}
|
||||
|
||||
// ExitNumberExpression is called when production numberExpression is exited.
|
||||
func (s *BaseAggregationExpressionListener) ExitNumberExpression(ctx *NumberExpressionContext) {}
|
||||
|
||||
// EnterMultiplicativeExpression is called when production multiplicativeExpression is entered.
|
||||
func (s *BaseAggregationExpressionListener) EnterMultiplicativeExpression(ctx *MultiplicativeExpressionContext) {
|
||||
}
|
||||
|
||||
// ExitMultiplicativeExpression is called when production multiplicativeExpression is exited.
|
||||
func (s *BaseAggregationExpressionListener) ExitMultiplicativeExpression(ctx *MultiplicativeExpressionContext) {
|
||||
}
|
||||
|
||||
// EnterUnaryExpression is called when production unaryExpression is entered.
|
||||
func (s *BaseAggregationExpressionListener) EnterUnaryExpression(ctx *UnaryExpressionContext) {}
|
||||
|
||||
// ExitUnaryExpression is called when production unaryExpression is exited.
|
||||
func (s *BaseAggregationExpressionListener) ExitUnaryExpression(ctx *UnaryExpressionContext) {}
|
||||
|
||||
// EnterFunctionExpression is called when production functionExpression is entered.
|
||||
func (s *BaseAggregationExpressionListener) EnterFunctionExpression(ctx *FunctionExpressionContext) {}
|
||||
|
||||
// ExitFunctionExpression is called when production functionExpression is exited.
|
||||
func (s *BaseAggregationExpressionListener) ExitFunctionExpression(ctx *FunctionExpressionContext) {}
|
||||
|
||||
// EnterFunctionCall is called when production functionCall is entered.
|
||||
func (s *BaseAggregationExpressionListener) EnterFunctionCall(ctx *FunctionCallContext) {}
|
||||
|
||||
// ExitFunctionCall is called when production functionCall is exited.
|
||||
func (s *BaseAggregationExpressionListener) ExitFunctionCall(ctx *FunctionCallContext) {}
|
||||
|
||||
// EnterArgumentList is called when production argumentList is entered.
|
||||
func (s *BaseAggregationExpressionListener) EnterArgumentList(ctx *ArgumentListContext) {}
|
||||
|
||||
// ExitArgumentList is called when production argumentList is exited.
|
||||
func (s *BaseAggregationExpressionListener) ExitArgumentList(ctx *ArgumentListContext) {}
|
||||
|
||||
// EnterArgument is called when production argument is entered.
|
||||
func (s *BaseAggregationExpressionListener) EnterArgument(ctx *ArgumentContext) {}
|
||||
|
||||
// ExitArgument is called when production argument is exited.
|
||||
func (s *BaseAggregationExpressionListener) ExitArgument(ctx *ArgumentContext) {}
|
||||
|
||||
// EnterArgumentToken is called when production argumentToken is entered.
|
||||
func (s *BaseAggregationExpressionListener) EnterArgumentToken(ctx *ArgumentTokenContext) {}
|
||||
|
||||
// ExitArgumentToken is called when production argumentToken is exited.
|
||||
func (s *BaseAggregationExpressionListener) ExitArgumentToken(ctx *ArgumentTokenContext) {}
|
||||
@@ -0,0 +1,53 @@
|
||||
// Code generated from grammar/AggregationExpression.g4 by ANTLR 4.13.2. DO NOT EDIT.
|
||||
|
||||
package parser // AggregationExpression
|
||||
|
||||
import "github.com/antlr4-go/antlr/v4"
|
||||
|
||||
type BaseAggregationExpressionVisitor struct {
|
||||
*antlr.BaseParseTreeVisitor
|
||||
}
|
||||
|
||||
func (v *BaseAggregationExpressionVisitor) VisitQuery(ctx *QueryContext) interface{} {
|
||||
return v.VisitChildren(ctx)
|
||||
}
|
||||
|
||||
func (v *BaseAggregationExpressionVisitor) VisitParenthesizedExpression(ctx *ParenthesizedExpressionContext) interface{} {
|
||||
return v.VisitChildren(ctx)
|
||||
}
|
||||
|
||||
func (v *BaseAggregationExpressionVisitor) VisitAdditiveExpression(ctx *AdditiveExpressionContext) interface{} {
|
||||
return v.VisitChildren(ctx)
|
||||
}
|
||||
|
||||
func (v *BaseAggregationExpressionVisitor) VisitNumberExpression(ctx *NumberExpressionContext) interface{} {
|
||||
return v.VisitChildren(ctx)
|
||||
}
|
||||
|
||||
func (v *BaseAggregationExpressionVisitor) VisitMultiplicativeExpression(ctx *MultiplicativeExpressionContext) interface{} {
|
||||
return v.VisitChildren(ctx)
|
||||
}
|
||||
|
||||
func (v *BaseAggregationExpressionVisitor) VisitUnaryExpression(ctx *UnaryExpressionContext) interface{} {
|
||||
return v.VisitChildren(ctx)
|
||||
}
|
||||
|
||||
func (v *BaseAggregationExpressionVisitor) VisitFunctionExpression(ctx *FunctionExpressionContext) interface{} {
|
||||
return v.VisitChildren(ctx)
|
||||
}
|
||||
|
||||
func (v *BaseAggregationExpressionVisitor) VisitFunctionCall(ctx *FunctionCallContext) interface{} {
|
||||
return v.VisitChildren(ctx)
|
||||
}
|
||||
|
||||
func (v *BaseAggregationExpressionVisitor) VisitArgumentList(ctx *ArgumentListContext) interface{} {
|
||||
return v.VisitChildren(ctx)
|
||||
}
|
||||
|
||||
func (v *BaseAggregationExpressionVisitor) VisitArgument(ctx *ArgumentContext) interface{} {
|
||||
return v.VisitChildren(ctx)
|
||||
}
|
||||
|
||||
func (v *BaseAggregationExpressionVisitor) VisitArgumentToken(ctx *ArgumentTokenContext) interface{} {
|
||||
return v.VisitChildren(ctx)
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
// Code generated from grammar/AggregationExpression.g4 by ANTLR 4.13.2. DO NOT EDIT.
|
||||
|
||||
package parser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/antlr4-go/antlr/v4"
|
||||
"sync"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
// Suppress unused import error
|
||||
var _ = fmt.Printf
|
||||
var _ = sync.Once{}
|
||||
var _ = unicode.IsLetter
|
||||
|
||||
type AggregationExpressionLexer struct {
|
||||
*antlr.BaseLexer
|
||||
channelNames []string
|
||||
modeNames []string
|
||||
// TODO: EOF string
|
||||
}
|
||||
|
||||
var AggregationExpressionLexerLexerStaticData struct {
|
||||
once sync.Once
|
||||
serializedATN []int32
|
||||
ChannelNames []string
|
||||
ModeNames []string
|
||||
LiteralNames []string
|
||||
SymbolicNames []string
|
||||
RuleNames []string
|
||||
PredictionContextCache *antlr.PredictionContextCache
|
||||
atn *antlr.ATN
|
||||
decisionToDFA []*antlr.DFA
|
||||
}
|
||||
|
||||
func aggregationexpressionlexerLexerInit() {
|
||||
staticData := &AggregationExpressionLexerLexerStaticData
|
||||
staticData.ChannelNames = []string{
|
||||
"DEFAULT_TOKEN_CHANNEL", "HIDDEN",
|
||||
}
|
||||
staticData.ModeNames = []string{
|
||||
"DEFAULT_MODE",
|
||||
}
|
||||
staticData.LiteralNames = []string{
|
||||
"", "'('", "')'", "'['", "']'", "','", "'+'", "'-'", "'*'", "'/'", "'%'",
|
||||
}
|
||||
staticData.SymbolicNames = []string{
|
||||
"", "LPAREN", "RPAREN", "LBRACK", "RBRACK", "COMMA", "PLUS", "MINUS",
|
||||
"STAR", "SLASH", "PERCENT", "OPERATOR", "NUMBER", "QUOTED_TEXT", "KEY",
|
||||
"WS", "OTHER",
|
||||
}
|
||||
staticData.RuleNames = []string{
|
||||
"LPAREN", "RPAREN", "LBRACK", "RBRACK", "COMMA", "PLUS", "MINUS", "STAR",
|
||||
"SLASH", "PERCENT", "OPERATOR", "NUMBER", "QUOTED_TEXT", "SEGMENT",
|
||||
"EMPTY_BRACKS", "OLD_JSON_BRACKS", "KEY", "WS", "DIGIT", "OTHER",
|
||||
}
|
||||
staticData.PredictionContextCache = antlr.NewPredictionContextCache()
|
||||
staticData.serializedATN = []int32{
|
||||
4, 0, 16, 183, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2,
|
||||
4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 2, 8, 7, 8, 2, 9, 7, 9, 2,
|
||||
10, 7, 10, 2, 11, 7, 11, 2, 12, 7, 12, 2, 13, 7, 13, 2, 14, 7, 14, 2, 15,
|
||||
7, 15, 2, 16, 7, 16, 2, 17, 7, 17, 2, 18, 7, 18, 2, 19, 7, 19, 1, 0, 1,
|
||||
0, 1, 1, 1, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 1, 4, 1, 5, 1, 5, 1, 6, 1,
|
||||
6, 1, 7, 1, 7, 1, 8, 1, 8, 1, 9, 1, 9, 1, 10, 1, 10, 1, 10, 1, 10, 1, 10,
|
||||
1, 10, 1, 10, 1, 10, 1, 10, 1, 10, 1, 10, 1, 10, 1, 10, 3, 10, 75, 8, 10,
|
||||
1, 11, 4, 11, 78, 8, 11, 11, 11, 12, 11, 79, 1, 11, 1, 11, 5, 11, 84, 8,
|
||||
11, 10, 11, 12, 11, 87, 9, 11, 3, 11, 89, 8, 11, 1, 11, 1, 11, 3, 11, 93,
|
||||
8, 11, 1, 11, 4, 11, 96, 8, 11, 11, 11, 12, 11, 97, 3, 11, 100, 8, 11,
|
||||
1, 11, 1, 11, 4, 11, 104, 8, 11, 11, 11, 12, 11, 105, 1, 11, 1, 11, 3,
|
||||
11, 110, 8, 11, 1, 11, 4, 11, 113, 8, 11, 11, 11, 12, 11, 114, 3, 11, 117,
|
||||
8, 11, 3, 11, 119, 8, 11, 1, 12, 1, 12, 1, 12, 1, 12, 5, 12, 125, 8, 12,
|
||||
10, 12, 12, 12, 128, 9, 12, 1, 12, 1, 12, 1, 12, 1, 12, 1, 12, 5, 12, 135,
|
||||
8, 12, 10, 12, 12, 12, 138, 9, 12, 1, 12, 3, 12, 141, 8, 12, 1, 13, 1,
|
||||
13, 5, 13, 145, 8, 13, 10, 13, 12, 13, 148, 9, 13, 1, 14, 1, 14, 1, 14,
|
||||
1, 15, 1, 15, 1, 15, 1, 15, 1, 16, 1, 16, 1, 16, 1, 16, 1, 16, 1, 16, 1,
|
||||
16, 4, 16, 164, 8, 16, 11, 16, 12, 16, 165, 5, 16, 168, 8, 16, 10, 16,
|
||||
12, 16, 171, 9, 16, 1, 17, 4, 17, 174, 8, 17, 11, 17, 12, 17, 175, 1, 17,
|
||||
1, 17, 1, 18, 1, 18, 1, 19, 1, 19, 0, 0, 20, 1, 1, 3, 2, 5, 3, 7, 4, 9,
|
||||
5, 11, 6, 13, 7, 15, 8, 17, 9, 19, 10, 21, 11, 23, 12, 25, 13, 27, 0, 29,
|
||||
0, 31, 0, 33, 14, 35, 15, 37, 0, 39, 16, 1, 0, 8, 2, 0, 69, 69, 101, 101,
|
||||
2, 0, 43, 43, 45, 45, 2, 0, 34, 34, 92, 92, 2, 0, 39, 39, 92, 92, 4, 0,
|
||||
35, 36, 64, 90, 95, 95, 97, 123, 7, 0, 35, 36, 45, 45, 47, 58, 64, 90,
|
||||
95, 95, 97, 123, 125, 125, 3, 0, 9, 10, 13, 13, 32, 32, 1, 0, 48, 57, 208,
|
||||
0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, 0, 7, 1, 0, 0, 0,
|
||||
0, 9, 1, 0, 0, 0, 0, 11, 1, 0, 0, 0, 0, 13, 1, 0, 0, 0, 0, 15, 1, 0, 0,
|
||||
0, 0, 17, 1, 0, 0, 0, 0, 19, 1, 0, 0, 0, 0, 21, 1, 0, 0, 0, 0, 23, 1, 0,
|
||||
0, 0, 0, 25, 1, 0, 0, 0, 0, 33, 1, 0, 0, 0, 0, 35, 1, 0, 0, 0, 0, 39, 1,
|
||||
0, 0, 0, 1, 41, 1, 0, 0, 0, 3, 43, 1, 0, 0, 0, 5, 45, 1, 0, 0, 0, 7, 47,
|
||||
1, 0, 0, 0, 9, 49, 1, 0, 0, 0, 11, 51, 1, 0, 0, 0, 13, 53, 1, 0, 0, 0,
|
||||
15, 55, 1, 0, 0, 0, 17, 57, 1, 0, 0, 0, 19, 59, 1, 0, 0, 0, 21, 74, 1,
|
||||
0, 0, 0, 23, 118, 1, 0, 0, 0, 25, 140, 1, 0, 0, 0, 27, 142, 1, 0, 0, 0,
|
||||
29, 149, 1, 0, 0, 0, 31, 152, 1, 0, 0, 0, 33, 156, 1, 0, 0, 0, 35, 173,
|
||||
1, 0, 0, 0, 37, 179, 1, 0, 0, 0, 39, 181, 1, 0, 0, 0, 41, 42, 5, 40, 0,
|
||||
0, 42, 2, 1, 0, 0, 0, 43, 44, 5, 41, 0, 0, 44, 4, 1, 0, 0, 0, 45, 46, 5,
|
||||
91, 0, 0, 46, 6, 1, 0, 0, 0, 47, 48, 5, 93, 0, 0, 48, 8, 1, 0, 0, 0, 49,
|
||||
50, 5, 44, 0, 0, 50, 10, 1, 0, 0, 0, 51, 52, 5, 43, 0, 0, 52, 12, 1, 0,
|
||||
0, 0, 53, 54, 5, 45, 0, 0, 54, 14, 1, 0, 0, 0, 55, 56, 5, 42, 0, 0, 56,
|
||||
16, 1, 0, 0, 0, 57, 58, 5, 47, 0, 0, 58, 18, 1, 0, 0, 0, 59, 60, 5, 37,
|
||||
0, 0, 60, 20, 1, 0, 0, 0, 61, 75, 5, 61, 0, 0, 62, 63, 5, 61, 0, 0, 63,
|
||||
75, 5, 61, 0, 0, 64, 65, 5, 33, 0, 0, 65, 75, 5, 61, 0, 0, 66, 67, 5, 60,
|
||||
0, 0, 67, 75, 5, 62, 0, 0, 68, 75, 5, 60, 0, 0, 69, 70, 5, 60, 0, 0, 70,
|
||||
75, 5, 61, 0, 0, 71, 75, 5, 62, 0, 0, 72, 73, 5, 62, 0, 0, 73, 75, 5, 61,
|
||||
0, 0, 74, 61, 1, 0, 0, 0, 74, 62, 1, 0, 0, 0, 74, 64, 1, 0, 0, 0, 74, 66,
|
||||
1, 0, 0, 0, 74, 68, 1, 0, 0, 0, 74, 69, 1, 0, 0, 0, 74, 71, 1, 0, 0, 0,
|
||||
74, 72, 1, 0, 0, 0, 75, 22, 1, 0, 0, 0, 76, 78, 3, 37, 18, 0, 77, 76, 1,
|
||||
0, 0, 0, 78, 79, 1, 0, 0, 0, 79, 77, 1, 0, 0, 0, 79, 80, 1, 0, 0, 0, 80,
|
||||
88, 1, 0, 0, 0, 81, 85, 5, 46, 0, 0, 82, 84, 3, 37, 18, 0, 83, 82, 1, 0,
|
||||
0, 0, 84, 87, 1, 0, 0, 0, 85, 83, 1, 0, 0, 0, 85, 86, 1, 0, 0, 0, 86, 89,
|
||||
1, 0, 0, 0, 87, 85, 1, 0, 0, 0, 88, 81, 1, 0, 0, 0, 88, 89, 1, 0, 0, 0,
|
||||
89, 99, 1, 0, 0, 0, 90, 92, 7, 0, 0, 0, 91, 93, 7, 1, 0, 0, 92, 91, 1,
|
||||
0, 0, 0, 92, 93, 1, 0, 0, 0, 93, 95, 1, 0, 0, 0, 94, 96, 3, 37, 18, 0,
|
||||
95, 94, 1, 0, 0, 0, 96, 97, 1, 0, 0, 0, 97, 95, 1, 0, 0, 0, 97, 98, 1,
|
||||
0, 0, 0, 98, 100, 1, 0, 0, 0, 99, 90, 1, 0, 0, 0, 99, 100, 1, 0, 0, 0,
|
||||
100, 119, 1, 0, 0, 0, 101, 103, 5, 46, 0, 0, 102, 104, 3, 37, 18, 0, 103,
|
||||
102, 1, 0, 0, 0, 104, 105, 1, 0, 0, 0, 105, 103, 1, 0, 0, 0, 105, 106,
|
||||
1, 0, 0, 0, 106, 116, 1, 0, 0, 0, 107, 109, 7, 0, 0, 0, 108, 110, 7, 1,
|
||||
0, 0, 109, 108, 1, 0, 0, 0, 109, 110, 1, 0, 0, 0, 110, 112, 1, 0, 0, 0,
|
||||
111, 113, 3, 37, 18, 0, 112, 111, 1, 0, 0, 0, 113, 114, 1, 0, 0, 0, 114,
|
||||
112, 1, 0, 0, 0, 114, 115, 1, 0, 0, 0, 115, 117, 1, 0, 0, 0, 116, 107,
|
||||
1, 0, 0, 0, 116, 117, 1, 0, 0, 0, 117, 119, 1, 0, 0, 0, 118, 77, 1, 0,
|
||||
0, 0, 118, 101, 1, 0, 0, 0, 119, 24, 1, 0, 0, 0, 120, 126, 5, 34, 0, 0,
|
||||
121, 125, 8, 2, 0, 0, 122, 123, 5, 92, 0, 0, 123, 125, 9, 0, 0, 0, 124,
|
||||
121, 1, 0, 0, 0, 124, 122, 1, 0, 0, 0, 125, 128, 1, 0, 0, 0, 126, 124,
|
||||
1, 0, 0, 0, 126, 127, 1, 0, 0, 0, 127, 129, 1, 0, 0, 0, 128, 126, 1, 0,
|
||||
0, 0, 129, 141, 5, 34, 0, 0, 130, 136, 5, 39, 0, 0, 131, 135, 8, 3, 0,
|
||||
0, 132, 133, 5, 92, 0, 0, 133, 135, 9, 0, 0, 0, 134, 131, 1, 0, 0, 0, 134,
|
||||
132, 1, 0, 0, 0, 135, 138, 1, 0, 0, 0, 136, 134, 1, 0, 0, 0, 136, 137,
|
||||
1, 0, 0, 0, 137, 139, 1, 0, 0, 0, 138, 136, 1, 0, 0, 0, 139, 141, 5, 39,
|
||||
0, 0, 140, 120, 1, 0, 0, 0, 140, 130, 1, 0, 0, 0, 141, 26, 1, 0, 0, 0,
|
||||
142, 146, 7, 4, 0, 0, 143, 145, 7, 5, 0, 0, 144, 143, 1, 0, 0, 0, 145,
|
||||
148, 1, 0, 0, 0, 146, 144, 1, 0, 0, 0, 146, 147, 1, 0, 0, 0, 147, 28, 1,
|
||||
0, 0, 0, 148, 146, 1, 0, 0, 0, 149, 150, 5, 91, 0, 0, 150, 151, 5, 93,
|
||||
0, 0, 151, 30, 1, 0, 0, 0, 152, 153, 5, 91, 0, 0, 153, 154, 5, 42, 0, 0,
|
||||
154, 155, 5, 93, 0, 0, 155, 32, 1, 0, 0, 0, 156, 169, 3, 27, 13, 0, 157,
|
||||
158, 5, 46, 0, 0, 158, 168, 3, 27, 13, 0, 159, 168, 3, 29, 14, 0, 160,
|
||||
168, 3, 31, 15, 0, 161, 163, 5, 46, 0, 0, 162, 164, 3, 37, 18, 0, 163,
|
||||
162, 1, 0, 0, 0, 164, 165, 1, 0, 0, 0, 165, 163, 1, 0, 0, 0, 165, 166,
|
||||
1, 0, 0, 0, 166, 168, 1, 0, 0, 0, 167, 157, 1, 0, 0, 0, 167, 159, 1, 0,
|
||||
0, 0, 167, 160, 1, 0, 0, 0, 167, 161, 1, 0, 0, 0, 168, 171, 1, 0, 0, 0,
|
||||
169, 167, 1, 0, 0, 0, 169, 170, 1, 0, 0, 0, 170, 34, 1, 0, 0, 0, 171, 169,
|
||||
1, 0, 0, 0, 172, 174, 7, 6, 0, 0, 173, 172, 1, 0, 0, 0, 174, 175, 1, 0,
|
||||
0, 0, 175, 173, 1, 0, 0, 0, 175, 176, 1, 0, 0, 0, 176, 177, 1, 0, 0, 0,
|
||||
177, 178, 6, 17, 0, 0, 178, 36, 1, 0, 0, 0, 179, 180, 7, 7, 0, 0, 180,
|
||||
38, 1, 0, 0, 0, 181, 182, 9, 0, 0, 0, 182, 40, 1, 0, 0, 0, 23, 0, 74, 79,
|
||||
85, 88, 92, 97, 99, 105, 109, 114, 116, 118, 124, 126, 134, 136, 140, 146,
|
||||
165, 167, 169, 175, 1, 6, 0, 0,
|
||||
}
|
||||
deserializer := antlr.NewATNDeserializer(nil)
|
||||
staticData.atn = deserializer.Deserialize(staticData.serializedATN)
|
||||
atn := staticData.atn
|
||||
staticData.decisionToDFA = make([]*antlr.DFA, len(atn.DecisionToState))
|
||||
decisionToDFA := staticData.decisionToDFA
|
||||
for index, state := range atn.DecisionToState {
|
||||
decisionToDFA[index] = antlr.NewDFA(state, index)
|
||||
}
|
||||
}
|
||||
|
||||
// AggregationExpressionLexerInit initializes any static state used to implement AggregationExpressionLexer. By default the
|
||||
// static state used to implement the lexer is lazily initialized during the first call to
|
||||
// NewAggregationExpressionLexer(). You can call this function if you wish to initialize the static state ahead
|
||||
// of time.
|
||||
func AggregationExpressionLexerInit() {
|
||||
staticData := &AggregationExpressionLexerLexerStaticData
|
||||
staticData.once.Do(aggregationexpressionlexerLexerInit)
|
||||
}
|
||||
|
||||
// NewAggregationExpressionLexer produces a new lexer instance for the optional input antlr.CharStream.
|
||||
func NewAggregationExpressionLexer(input antlr.CharStream) *AggregationExpressionLexer {
|
||||
AggregationExpressionLexerInit()
|
||||
l := new(AggregationExpressionLexer)
|
||||
l.BaseLexer = antlr.NewBaseLexer(input)
|
||||
staticData := &AggregationExpressionLexerLexerStaticData
|
||||
l.Interpreter = antlr.NewLexerATNSimulator(l, staticData.atn, staticData.decisionToDFA, staticData.PredictionContextCache)
|
||||
l.channelNames = staticData.ChannelNames
|
||||
l.modeNames = staticData.ModeNames
|
||||
l.RuleNames = staticData.RuleNames
|
||||
l.LiteralNames = staticData.LiteralNames
|
||||
l.SymbolicNames = staticData.SymbolicNames
|
||||
l.GrammarFileName = "AggregationExpression.g4"
|
||||
// TODO: l.EOF = antlr.TokenEOF
|
||||
|
||||
return l
|
||||
}
|
||||
|
||||
// AggregationExpressionLexer tokens.
|
||||
const (
|
||||
AggregationExpressionLexerLPAREN = 1
|
||||
AggregationExpressionLexerRPAREN = 2
|
||||
AggregationExpressionLexerLBRACK = 3
|
||||
AggregationExpressionLexerRBRACK = 4
|
||||
AggregationExpressionLexerCOMMA = 5
|
||||
AggregationExpressionLexerPLUS = 6
|
||||
AggregationExpressionLexerMINUS = 7
|
||||
AggregationExpressionLexerSTAR = 8
|
||||
AggregationExpressionLexerSLASH = 9
|
||||
AggregationExpressionLexerPERCENT = 10
|
||||
AggregationExpressionLexerOPERATOR = 11
|
||||
AggregationExpressionLexerNUMBER = 12
|
||||
AggregationExpressionLexerQUOTED_TEXT = 13
|
||||
AggregationExpressionLexerKEY = 14
|
||||
AggregationExpressionLexerWS = 15
|
||||
AggregationExpressionLexerOTHER = 16
|
||||
)
|
||||
@@ -0,0 +1,76 @@
|
||||
// Code generated from grammar/AggregationExpression.g4 by ANTLR 4.13.2. DO NOT EDIT.
|
||||
|
||||
package parser // AggregationExpression
|
||||
|
||||
import "github.com/antlr4-go/antlr/v4"
|
||||
|
||||
// AggregationExpressionListener is a complete listener for a parse tree produced by AggregationExpressionParser.
|
||||
type AggregationExpressionListener interface {
|
||||
antlr.ParseTreeListener
|
||||
|
||||
// EnterQuery is called when entering the query production.
|
||||
EnterQuery(c *QueryContext)
|
||||
|
||||
// EnterParenthesizedExpression is called when entering the parenthesizedExpression production.
|
||||
EnterParenthesizedExpression(c *ParenthesizedExpressionContext)
|
||||
|
||||
// EnterAdditiveExpression is called when entering the additiveExpression production.
|
||||
EnterAdditiveExpression(c *AdditiveExpressionContext)
|
||||
|
||||
// EnterNumberExpression is called when entering the numberExpression production.
|
||||
EnterNumberExpression(c *NumberExpressionContext)
|
||||
|
||||
// EnterMultiplicativeExpression is called when entering the multiplicativeExpression production.
|
||||
EnterMultiplicativeExpression(c *MultiplicativeExpressionContext)
|
||||
|
||||
// EnterUnaryExpression is called when entering the unaryExpression production.
|
||||
EnterUnaryExpression(c *UnaryExpressionContext)
|
||||
|
||||
// EnterFunctionExpression is called when entering the functionExpression production.
|
||||
EnterFunctionExpression(c *FunctionExpressionContext)
|
||||
|
||||
// EnterFunctionCall is called when entering the functionCall production.
|
||||
EnterFunctionCall(c *FunctionCallContext)
|
||||
|
||||
// EnterArgumentList is called when entering the argumentList production.
|
||||
EnterArgumentList(c *ArgumentListContext)
|
||||
|
||||
// EnterArgument is called when entering the argument production.
|
||||
EnterArgument(c *ArgumentContext)
|
||||
|
||||
// EnterArgumentToken is called when entering the argumentToken production.
|
||||
EnterArgumentToken(c *ArgumentTokenContext)
|
||||
|
||||
// ExitQuery is called when exiting the query production.
|
||||
ExitQuery(c *QueryContext)
|
||||
|
||||
// ExitParenthesizedExpression is called when exiting the parenthesizedExpression production.
|
||||
ExitParenthesizedExpression(c *ParenthesizedExpressionContext)
|
||||
|
||||
// ExitAdditiveExpression is called when exiting the additiveExpression production.
|
||||
ExitAdditiveExpression(c *AdditiveExpressionContext)
|
||||
|
||||
// ExitNumberExpression is called when exiting the numberExpression production.
|
||||
ExitNumberExpression(c *NumberExpressionContext)
|
||||
|
||||
// ExitMultiplicativeExpression is called when exiting the multiplicativeExpression production.
|
||||
ExitMultiplicativeExpression(c *MultiplicativeExpressionContext)
|
||||
|
||||
// ExitUnaryExpression is called when exiting the unaryExpression production.
|
||||
ExitUnaryExpression(c *UnaryExpressionContext)
|
||||
|
||||
// ExitFunctionExpression is called when exiting the functionExpression production.
|
||||
ExitFunctionExpression(c *FunctionExpressionContext)
|
||||
|
||||
// ExitFunctionCall is called when exiting the functionCall production.
|
||||
ExitFunctionCall(c *FunctionCallContext)
|
||||
|
||||
// ExitArgumentList is called when exiting the argumentList production.
|
||||
ExitArgumentList(c *ArgumentListContext)
|
||||
|
||||
// ExitArgument is called when exiting the argument production.
|
||||
ExitArgument(c *ArgumentContext)
|
||||
|
||||
// ExitArgumentToken is called when exiting the argumentToken production.
|
||||
ExitArgumentToken(c *ArgumentTokenContext)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,43 @@
|
||||
// Code generated from grammar/AggregationExpression.g4 by ANTLR 4.13.2. DO NOT EDIT.
|
||||
|
||||
package parser // AggregationExpression
|
||||
|
||||
import "github.com/antlr4-go/antlr/v4"
|
||||
|
||||
// A complete Visitor for a parse tree produced by AggregationExpressionParser.
|
||||
type AggregationExpressionVisitor interface {
|
||||
antlr.ParseTreeVisitor
|
||||
|
||||
// Visit a parse tree produced by AggregationExpressionParser#query.
|
||||
VisitQuery(ctx *QueryContext) interface{}
|
||||
|
||||
// Visit a parse tree produced by AggregationExpressionParser#parenthesizedExpression.
|
||||
VisitParenthesizedExpression(ctx *ParenthesizedExpressionContext) interface{}
|
||||
|
||||
// Visit a parse tree produced by AggregationExpressionParser#additiveExpression.
|
||||
VisitAdditiveExpression(ctx *AdditiveExpressionContext) interface{}
|
||||
|
||||
// Visit a parse tree produced by AggregationExpressionParser#numberExpression.
|
||||
VisitNumberExpression(ctx *NumberExpressionContext) interface{}
|
||||
|
||||
// Visit a parse tree produced by AggregationExpressionParser#multiplicativeExpression.
|
||||
VisitMultiplicativeExpression(ctx *MultiplicativeExpressionContext) interface{}
|
||||
|
||||
// Visit a parse tree produced by AggregationExpressionParser#unaryExpression.
|
||||
VisitUnaryExpression(ctx *UnaryExpressionContext) interface{}
|
||||
|
||||
// Visit a parse tree produced by AggregationExpressionParser#functionExpression.
|
||||
VisitFunctionExpression(ctx *FunctionExpressionContext) interface{}
|
||||
|
||||
// Visit a parse tree produced by AggregationExpressionParser#functionCall.
|
||||
VisitFunctionCall(ctx *FunctionCallContext) interface{}
|
||||
|
||||
// Visit a parse tree produced by AggregationExpressionParser#argumentList.
|
||||
VisitArgumentList(ctx *ArgumentListContext) interface{}
|
||||
|
||||
// Visit a parse tree produced by AggregationExpressionParser#argument.
|
||||
VisitArgument(ctx *ArgumentContext) interface{}
|
||||
|
||||
// Visit a parse tree produced by AggregationExpressionParser#argumentToken.
|
||||
VisitArgumentToken(ctx *ArgumentTokenContext) interface{}
|
||||
}
|
||||
101
pkg/querybuilder/agg_expression.go
Normal file
101
pkg/querybuilder/agg_expression.go
Normal file
@@ -0,0 +1,101 @@
|
||||
package querybuilder
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
grammar "github.com/SigNoz/signoz/pkg/parser/aggregationexpression/grammar"
|
||||
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
|
||||
"github.com/SigNoz/signoz/pkg/valuer"
|
||||
"github.com/antlr4-go/antlr/v4"
|
||||
)
|
||||
|
||||
// AggregationKeySelectors returns the keys an aggregation expression reads: its
|
||||
// field arguments and the keys in a combinator's predicate. An expression the
|
||||
// grammar rejects falls back to every key token in it.
|
||||
func AggregationKeySelectors(expression string) []*telemetrytypes.FieldKeySelector {
|
||||
calls, err := parseAggregationExpression(expression)
|
||||
if err != nil {
|
||||
return QueryStringToKeysSelectors(expression)
|
||||
}
|
||||
|
||||
var selectors []*telemetrytypes.FieldKeySelector
|
||||
for _, args := range calls {
|
||||
for _, arg := range args {
|
||||
selectors = append(selectors, QueryStringToKeysSelectors(arg)...)
|
||||
}
|
||||
}
|
||||
return selectors
|
||||
}
|
||||
|
||||
// parseAggregationExpression parses an aggregation expression into the
|
||||
// arguments of each function call, as written. It checks each call as the
|
||||
// rewriter does: a known function and, for one that requires arguments, an
|
||||
// argument count in range. Only the first of comma-separated expressions is
|
||||
// read, since it is the only one the rewriter renders.
|
||||
func parseAggregationExpression(expression string) ([][]string, error) {
|
||||
input := antlr.NewInputStream(expression)
|
||||
|
||||
lexer := grammar.NewAggregationExpressionLexer(input)
|
||||
lexerErrors := NewErrorListener()
|
||||
lexer.RemoveErrorListeners()
|
||||
lexer.AddErrorListener(lexerErrors)
|
||||
|
||||
parser := grammar.NewAggregationExpressionParser(antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel))
|
||||
parserErrors := NewErrorListener()
|
||||
parser.RemoveErrorListeners()
|
||||
parser.AddErrorListener(parserErrors)
|
||||
|
||||
query := parser.Query()
|
||||
|
||||
if syntaxErrors := append(lexerErrors.SyntaxErrors, parserErrors.SyntaxErrors...); len(syntaxErrors) > 0 {
|
||||
messages := make([]string, 0, len(syntaxErrors))
|
||||
for _, syntaxError := range syntaxErrors {
|
||||
messages = append(messages, syntaxError.Error())
|
||||
}
|
||||
return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "syntax error in aggregation expression %q", expression).
|
||||
WithAdditional(messages...)
|
||||
}
|
||||
|
||||
var calls [][]string
|
||||
for _, functionCall := range collectFunctionCalls(query.Expression(0), nil) {
|
||||
name := strings.ToLower(functionCall.KEY().GetText())
|
||||
function, ok := AggreFuncMap[valuer.NewString(name)]
|
||||
if !ok {
|
||||
return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "unrecognized function: %s", name)
|
||||
}
|
||||
|
||||
var args []string
|
||||
if argumentList := functionCall.ArgumentList(); argumentList != nil {
|
||||
for _, argument := range argumentList.AllArgument() {
|
||||
args = append(args, input.GetText(argument.GetStart().GetStart(), argument.GetStop().GetStop()))
|
||||
}
|
||||
}
|
||||
if function.RequireArgs && (len(args) < function.MinArgs || len(args) > function.MaxArgs) {
|
||||
return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid number of arguments for %q: %d", name, len(args))
|
||||
}
|
||||
|
||||
calls = append(calls, args)
|
||||
}
|
||||
return calls, nil
|
||||
}
|
||||
|
||||
func collectFunctionCalls(expression grammar.IExpressionContext, calls []grammar.IFunctionCallContext) []grammar.IFunctionCallContext {
|
||||
switch e := expression.(type) {
|
||||
case *grammar.FunctionExpressionContext:
|
||||
calls = append(calls, e.FunctionCall())
|
||||
case *grammar.UnaryExpressionContext:
|
||||
calls = collectFunctionCalls(e.Expression(), calls)
|
||||
case *grammar.ParenthesizedExpressionContext:
|
||||
calls = collectFunctionCalls(e.Expression(), calls)
|
||||
case *grammar.AdditiveExpressionContext:
|
||||
for _, operand := range e.AllExpression() {
|
||||
calls = collectFunctionCalls(operand, calls)
|
||||
}
|
||||
case *grammar.MultiplicativeExpressionContext:
|
||||
for _, operand := range e.AllExpression() {
|
||||
calls = collectFunctionCalls(operand, calls)
|
||||
}
|
||||
}
|
||||
return calls
|
||||
}
|
||||
@@ -57,6 +57,10 @@ func (r *aggExprRewriter) Rewrite(
|
||||
keys map[string][]*telemetrytypes.TelemetryFieldKey,
|
||||
) (string, []any, error) {
|
||||
|
||||
if _, err := parseAggregationExpression(expr); err != nil {
|
||||
r.logger.WarnContext(ctx, "aggregation expression failed grammar validation", slog.String("expression", expr), errors.Attr(err))
|
||||
}
|
||||
|
||||
wrapped := fmt.Sprintf("SELECT %s", expr)
|
||||
p := chparser.NewParser(wrapped)
|
||||
stmts, err := p.ParseStmts()
|
||||
|
||||
@@ -128,7 +128,7 @@ func getKeySelectors(query qbtypes.QueryBuilderQuery[qbtypes.LogAggregation]) []
|
||||
|
||||
for idx := range query.Aggregations {
|
||||
aggExpr := query.Aggregations[idx]
|
||||
selectors := querybuilder.QueryStringToKeysSelectors(aggExpr.Expression)
|
||||
selectors := querybuilder.AggregationKeySelectors(aggExpr.Expression)
|
||||
keySelectors = append(keySelectors, selectors...)
|
||||
}
|
||||
|
||||
|
||||
@@ -179,7 +179,7 @@ func getKeySelectors(query qbtypes.QueryBuilderQuery[qbtypes.LogAggregation], bo
|
||||
|
||||
for idx := range query.Aggregations {
|
||||
aggExpr := query.Aggregations[idx]
|
||||
selectors := querybuilder.QueryStringToKeysSelectors(aggExpr.Expression)
|
||||
selectors := querybuilder.AggregationKeySelectors(aggExpr.Expression)
|
||||
keySelectors = append(keySelectors, selectors...)
|
||||
}
|
||||
|
||||
|
||||
@@ -192,7 +192,7 @@ func getKeySelectors(query qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation])
|
||||
|
||||
for idx := range query.Aggregations {
|
||||
aggExpr := query.Aggregations[idx]
|
||||
selectors := querybuilder.QueryStringToKeysSelectors(aggExpr.Expression)
|
||||
selectors := querybuilder.AggregationKeySelectors(aggExpr.Expression)
|
||||
keySelectors = append(keySelectors, selectors...)
|
||||
}
|
||||
|
||||
|
||||
@@ -582,7 +582,7 @@ func (b *traceOperatorCTEBuilder) getKeySelectors() []*telemetrytypes.FieldKeySe
|
||||
var keySelectors []*telemetrytypes.FieldKeySelector
|
||||
|
||||
for _, agg := range b.operator.Aggregations {
|
||||
selectors := querybuilder.QueryStringToKeysSelectors(agg.Expression)
|
||||
selectors := querybuilder.AggregationKeySelectors(agg.Expression)
|
||||
keySelectors = append(keySelectors, selectors...)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
package cloudintegrationtypes
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"text/template"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/valuer"
|
||||
)
|
||||
|
||||
const foundryScriptURL = "https://signoz.io/foundry.sh"
|
||||
type CloudProviderType struct{ valuer.String }
|
||||
|
||||
var (
|
||||
// cloud providers.
|
||||
@@ -17,16 +14,8 @@ var (
|
||||
CloudProviderTypeGCP = CloudProviderType{valuer.NewString("gcp")}
|
||||
|
||||
ErrCodeCloudProviderInvalidInput = errors.MustNewCode("cloud_integration_invalid_cloud_provider")
|
||||
|
||||
foundryTemplateFuncs = template.FuncMap{
|
||||
"shellQuote": func(value string) string {
|
||||
return "'" + strings.ReplaceAll(value, "'", "'\"'\"'") + "'"
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
type CloudProviderType struct{ valuer.String }
|
||||
|
||||
func NewCloudProvider(provider string) (CloudProviderType, error) {
|
||||
switch provider {
|
||||
case CloudProviderTypeAWS.StringValue():
|
||||
@@ -39,11 +28,3 @@ func NewCloudProvider(provider string) (CloudProviderType, error) {
|
||||
return CloudProviderType{}, errors.NewInvalidInputf(ErrCodeCloudProviderInvalidInput, "invalid cloud provider: %s", provider)
|
||||
}
|
||||
}
|
||||
|
||||
type foundryTemplateData struct {
|
||||
FoundryScriptURL string
|
||||
Region string
|
||||
IntegrationAccountID string
|
||||
AgentVersion string
|
||||
Credentials *Credentials
|
||||
}
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
package cloudintegrationtypes
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"text/template"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/valuer"
|
||||
)
|
||||
|
||||
var awsCLITemplate = template.Must(template.New("awsCLI").Funcs(foundryTemplateFuncs).Parse(awsCLITemplateStr()))
|
||||
var (
|
||||
CloudFormationQuickCreateBaseURL = valuer.NewString("https://%s.console.aws.amazon.com/cloudformation/home")
|
||||
AgentCloudFormationTemplateS3Path = valuer.NewString("https://signoz-integrations.s3.us-east-1.amazonaws.com/aws-quickcreate-template-%s.json")
|
||||
AgentCloudFormationBaseStackName = valuer.NewString("signoz-integration")
|
||||
)
|
||||
|
||||
type AWSPostableAccountConfig struct {
|
||||
DeploymentRegion string `json:"deploymentRegion" required:"true"`
|
||||
@@ -15,7 +16,7 @@ type AWSPostableAccountConfig struct {
|
||||
}
|
||||
|
||||
type AWSConnectionArtifact struct {
|
||||
CLICommand string `json:"cliCommand" required:"true"`
|
||||
ConnectionURL string `json:"connectionUrl" required:"true"`
|
||||
}
|
||||
|
||||
type AWSAccountConfig struct {
|
||||
@@ -104,23 +105,10 @@ type AWSServiceMetricsConfig struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
|
||||
func NewAWSConnectionArtifact(integrationAccountID valuer.UUID, agentVersion string, creds *Credentials, deploymentRegion string) (*AWSConnectionArtifact, error) {
|
||||
data := foundryTemplateData{
|
||||
FoundryScriptURL: foundryScriptURL,
|
||||
Region: deploymentRegion,
|
||||
IntegrationAccountID: integrationAccountID.StringValue(),
|
||||
AgentVersion: agentVersion,
|
||||
Credentials: creds,
|
||||
}
|
||||
|
||||
var command bytes.Buffer
|
||||
if err := awsCLITemplate.Execute(&command, data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func NewAWSConnectionArtifact(connectionURL string) *AWSConnectionArtifact {
|
||||
return &AWSConnectionArtifact{
|
||||
CLICommand: command.String(),
|
||||
}, nil
|
||||
ConnectionURL: connectionURL,
|
||||
}
|
||||
}
|
||||
|
||||
func NewAWSIntegrationConfig(enabledRegions []string, telemetryCollectionStrategy *AWSTelemetryCollectionStrategy) *AWSIntegrationConfig {
|
||||
@@ -179,14 +167,3 @@ func awsOlderIntegrationConfig(cfg *ProviderIntegrationConfig) *IntegrationConfi
|
||||
older.Telemetry = oldTelemetry
|
||||
return older
|
||||
}
|
||||
|
||||
func awsCLITemplateStr() string {
|
||||
return `curl -fsSL {{.FoundryScriptURL | shellQuote}} | bash -s -- cloudintegration aws cloudformation \
|
||||
--region {{.Region | shellQuote}} \
|
||||
--integration-account-id {{.IntegrationAccountID | shellQuote}} \
|
||||
--signoz-api-url {{.Credentials.SigNozAPIURL | shellQuote}} \
|
||||
--signoz-api-key {{.Credentials.SigNozAPIKey | shellQuote}} \
|
||||
--ingestion-url {{.Credentials.IngestionURL | shellQuote}} \
|
||||
--ingestion-key {{.Credentials.IngestionKey | shellQuote}} \
|
||||
--agent-version {{.AgentVersion | shellQuote}}`
|
||||
}
|
||||
|
||||
@@ -2,12 +2,37 @@ package cloudintegrationtypes
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"text/template"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/valuer"
|
||||
)
|
||||
|
||||
var azureCLITemplate = template.Must(template.New("azureCLI").Funcs(foundryTemplateFuncs).Parse(azureCLITemplateStr()))
|
||||
var (
|
||||
AgentArmTemplateStorePath = "https://signoz-integrations.s3.us-east-1.amazonaws.com/azure-arm-template-%s.json"
|
||||
AgentDeploymentStackName = "signoz-integration"
|
||||
|
||||
// Default values for fixed ARM template parameters.
|
||||
armDefaultRgName = "signoz-integration-rg"
|
||||
armDefaultContainerEnvName = "signoz-integration-agent-env"
|
||||
armDefaultDeploymentEnv = "production"
|
||||
|
||||
// ARM template parameter key names used in both CLI and PowerShell deployment commands.
|
||||
armParamLocation = "location"
|
||||
armParamSignozAPIKey = "signozApiKey"
|
||||
armParamSignozAPIUrl = "signozApiUrl"
|
||||
armParamSignozIngestionURL = "signozIngestionUrl"
|
||||
armParamSignozIngestionKey = "signozIngestionKey"
|
||||
armParamAccountID = "signozIntegrationAccountId"
|
||||
armParamAgentVersion = "signozIntegrationAgentVersion"
|
||||
armParamRgName = "rgName"
|
||||
armParamContainerEnvName = "containerEnvName"
|
||||
armParamDeploymentEnv = "deploymentEnv"
|
||||
|
||||
// command templates.
|
||||
azureCLITemplate = template.Must(template.New("azureCLI").Parse(azureCLITemplateStr()))
|
||||
azurePowerShellTemplate = template.Must(template.New("azurePS").Parse(azurePowerShellTemplateStr()))
|
||||
)
|
||||
|
||||
type AzureAccountConfig struct {
|
||||
DeploymentRegion string `json:"deploymentRegion" required:"true"`
|
||||
@@ -21,7 +46,8 @@ type UpdatableAzureAccountConfig struct {
|
||||
type AzurePostableAccountConfig = AzureAccountConfig
|
||||
|
||||
type AzureConnectionArtifact struct {
|
||||
CLICommand string `json:"cliCommand" required:"true"`
|
||||
CLICommand string `json:"cliCommand" required:"true"`
|
||||
CloudPowerShellCommand string `json:"cloudPowerShellCommand" required:"true"`
|
||||
}
|
||||
|
||||
type AzureServiceConfig struct {
|
||||
@@ -59,6 +85,36 @@ type AzureIntegrationConfig struct {
|
||||
TelemetryCollectionStrategy []*AzureTelemetryCollectionStrategy `json:"telemetryCollectionStrategy" required:"true" nullable:"false"`
|
||||
}
|
||||
|
||||
// azureTemplateData is the data struct passed to both command templates.
|
||||
// All fields are exported so text/template can access them.
|
||||
type azureTemplateData struct {
|
||||
// Deploy parameter values.
|
||||
TemplateURL string
|
||||
Location string
|
||||
SignozAPIKey string
|
||||
SignozAPIUrl string
|
||||
SignozIngestionURL string
|
||||
SignozIngestionKey string
|
||||
AccountID string
|
||||
AgentVersion string
|
||||
// ARM parameter key names (from package-level vars).
|
||||
StackName string
|
||||
ParamLocation string
|
||||
ParamSignozAPIKey string
|
||||
ParamSignozAPIUrl string
|
||||
ParamSignozIngestionURL string
|
||||
ParamSignozIngestionKey string
|
||||
ParamAccountID string
|
||||
ParamAgentVersion string
|
||||
ParamRgName string
|
||||
ParamContainerEnvName string
|
||||
ParamDeploymentEnv string
|
||||
// Fixed default values.
|
||||
DefaultRgName string
|
||||
DefaultContainerEnvName string
|
||||
DefaultDeploymentEnv string
|
||||
}
|
||||
|
||||
func NewAzureIntegrationConfig(
|
||||
deploymentRegion string,
|
||||
resourceGroups []string,
|
||||
@@ -71,32 +127,104 @@ func NewAzureIntegrationConfig(
|
||||
}
|
||||
}
|
||||
|
||||
func NewAzureConnectionArtifact(integrationAccountID valuer.UUID, agentVersion string, creds *Credentials, cfg *AzurePostableAccountConfig) (*AzureConnectionArtifact, error) {
|
||||
data := foundryTemplateData{
|
||||
FoundryScriptURL: foundryScriptURL,
|
||||
Region: cfg.DeploymentRegion,
|
||||
IntegrationAccountID: integrationAccountID.StringValue(),
|
||||
AgentVersion: agentVersion,
|
||||
Credentials: creds,
|
||||
func NewAzureConnectionArtifact(
|
||||
accountID valuer.UUID,
|
||||
agentVersion string,
|
||||
creds *Credentials,
|
||||
cfg *AzurePostableAccountConfig,
|
||||
) (*AzureConnectionArtifact, error) {
|
||||
data := azureTemplateData{
|
||||
TemplateURL: fmt.Sprintf(AgentArmTemplateStorePath, agentVersion),
|
||||
Location: cfg.DeploymentRegion,
|
||||
SignozAPIKey: creds.SigNozAPIKey,
|
||||
SignozAPIUrl: creds.SigNozAPIURL,
|
||||
SignozIngestionURL: creds.IngestionURL,
|
||||
SignozIngestionKey: creds.IngestionKey,
|
||||
AccountID: accountID.StringValue(),
|
||||
AgentVersion: agentVersion,
|
||||
StackName: AgentDeploymentStackName,
|
||||
ParamLocation: armParamLocation,
|
||||
ParamSignozAPIKey: armParamSignozAPIKey,
|
||||
ParamSignozAPIUrl: armParamSignozAPIUrl,
|
||||
ParamSignozIngestionURL: armParamSignozIngestionURL,
|
||||
ParamSignozIngestionKey: armParamSignozIngestionKey,
|
||||
ParamAccountID: armParamAccountID,
|
||||
ParamAgentVersion: armParamAgentVersion,
|
||||
ParamRgName: armParamRgName,
|
||||
ParamContainerEnvName: armParamContainerEnvName,
|
||||
ParamDeploymentEnv: armParamDeploymentEnv,
|
||||
DefaultRgName: armDefaultRgName,
|
||||
DefaultContainerEnvName: armDefaultContainerEnvName,
|
||||
DefaultDeploymentEnv: armDefaultDeploymentEnv,
|
||||
}
|
||||
|
||||
var command bytes.Buffer
|
||||
if err := azureCLITemplate.Execute(&command, data); err != nil {
|
||||
cliCommand, err := newAzureConnectionCLICommand(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
psCommand, err := newAzureConnectionPowerShellCommand(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &AzureConnectionArtifact{
|
||||
CLICommand: command.String(),
|
||||
CLICommand: cliCommand,
|
||||
CloudPowerShellCommand: psCommand,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func azureCLITemplateStr() string {
|
||||
return `curl -fsSL {{.FoundryScriptURL | shellQuote}} | bash -s -- cloudintegration azure bicep \
|
||||
--region {{.Region | shellQuote}} \
|
||||
--integration-account-id {{.IntegrationAccountID | shellQuote}} \
|
||||
--signoz-api-url {{.Credentials.SigNozAPIURL | shellQuote}} \
|
||||
--signoz-api-key {{.Credentials.SigNozAPIKey | shellQuote}} \
|
||||
--ingestion-url {{.Credentials.IngestionURL | shellQuote}} \
|
||||
--ingestion-key {{.Credentials.IngestionKey | shellQuote}} \
|
||||
--agent-version {{.AgentVersion | shellQuote}}`
|
||||
func newAzureConnectionCLICommand(data azureTemplateData) (string, error) {
|
||||
var buf bytes.Buffer
|
||||
err := azureCLITemplate.Execute(&buf, data)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return buf.String(), nil
|
||||
}
|
||||
|
||||
func newAzureConnectionPowerShellCommand(data azureTemplateData) (string, error) {
|
||||
var buf bytes.Buffer
|
||||
err := azurePowerShellTemplate.Execute(&buf, data)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return buf.String(), nil
|
||||
}
|
||||
|
||||
func azureCLITemplateStr() string {
|
||||
return `az stack sub create \
|
||||
--name {{.StackName}} \
|
||||
--location {{.Location}} \
|
||||
--template-uri {{.TemplateURL}} \
|
||||
--parameters \
|
||||
{{.ParamLocation}}='{{.Location}}' \
|
||||
{{.ParamSignozAPIKey}}='{{.SignozAPIKey}}' \
|
||||
{{.ParamSignozAPIUrl}}='{{.SignozAPIUrl}}' \
|
||||
{{.ParamSignozIngestionURL}}='{{.SignozIngestionURL}}' \
|
||||
{{.ParamSignozIngestionKey}}='{{.SignozIngestionKey}}' \
|
||||
{{.ParamAccountID}}='{{.AccountID}}' \
|
||||
{{.ParamAgentVersion}}='{{.AgentVersion}}' \
|
||||
--action-on-unmanage deleteAll \
|
||||
--deny-settings-mode denyDelete`
|
||||
}
|
||||
|
||||
func azurePowerShellTemplateStr() string {
|
||||
return "New-AzSubscriptionDeploymentStack `\n" +
|
||||
" -Name \"{{.StackName}}\" `\n" +
|
||||
" -Location \"{{.Location}}\" `\n" +
|
||||
" -TemplateUri \"{{.TemplateURL}}\" `\n" +
|
||||
" -TemplateParameterObject @{\n" +
|
||||
" {{.ParamLocation}} = \"{{.Location}}\"\n" +
|
||||
" {{.ParamSignozAPIKey}} = \"{{.SignozAPIKey}}\"\n" +
|
||||
" {{.ParamSignozAPIUrl}} = \"{{.SignozAPIUrl}}\"\n" +
|
||||
" {{.ParamSignozIngestionURL}} = \"{{.SignozIngestionURL}}\"\n" +
|
||||
" {{.ParamSignozIngestionKey}} = \"{{.SignozIngestionKey}}\"\n" +
|
||||
" {{.ParamAccountID}} = \"{{.AccountID}}\"\n" +
|
||||
" {{.ParamAgentVersion}} = \"{{.AgentVersion}}\"\n" +
|
||||
" {{.ParamRgName}} = \"{{.DefaultRgName}}\"\n" +
|
||||
" {{.ParamContainerEnvName}} = \"{{.DefaultContainerEnvName}}\"\n" +
|
||||
" {{.ParamDeploymentEnv}} = \"{{.DefaultDeploymentEnv}}\"\n" +
|
||||
" } `\n" +
|
||||
" -ActionOnUnmanage \"deleteAll\" `\n" +
|
||||
" -DenySettingsMode \"denyDelete\""
|
||||
}
|
||||
|
||||
142
pkg/types/cloudintegrationtypes/cloudprovider_azure_test.go
Normal file
142
pkg/types/cloudintegrationtypes/cloudprovider_azure_test.go
Normal file
@@ -0,0 +1,142 @@
|
||||
// file is generated by AI
|
||||
package cloudintegrationtypes
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/valuer"
|
||||
)
|
||||
|
||||
var testTemplateData = azureTemplateData{
|
||||
TemplateURL: fmt.Sprintf(AgentArmTemplateStorePath, "v0.1.0"),
|
||||
Location: "eastus",
|
||||
SignozAPIKey: "test-api-key",
|
||||
SignozAPIUrl: "https://signoz.example.com",
|
||||
SignozIngestionURL: "https://ingest.example.com",
|
||||
SignozIngestionKey: "test-ingest-key",
|
||||
AccountID: "acct-123",
|
||||
AgentVersion: "v0.1.0",
|
||||
StackName: AgentDeploymentStackName,
|
||||
ParamLocation: armParamLocation,
|
||||
ParamSignozAPIKey: armParamSignozAPIKey,
|
||||
ParamSignozAPIUrl: armParamSignozAPIUrl,
|
||||
ParamSignozIngestionURL: armParamSignozIngestionURL,
|
||||
ParamSignozIngestionKey: armParamSignozIngestionKey,
|
||||
ParamAccountID: armParamAccountID,
|
||||
ParamAgentVersion: armParamAgentVersion,
|
||||
ParamRgName: armParamRgName,
|
||||
ParamContainerEnvName: armParamContainerEnvName,
|
||||
ParamDeploymentEnv: armParamDeploymentEnv,
|
||||
DefaultRgName: armDefaultRgName,
|
||||
DefaultContainerEnvName: armDefaultContainerEnvName,
|
||||
DefaultDeploymentEnv: armDefaultDeploymentEnv,
|
||||
}
|
||||
|
||||
func TestNewAzureConnectionCLICommand(t *testing.T) {
|
||||
cmd, err := newAzureConnectionCLICommand(testTemplateData)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
mustContain := []string{
|
||||
"az stack sub create",
|
||||
fmt.Sprintf("--name %s", AgentDeploymentStackName),
|
||||
fmt.Sprintf("--location %s", testTemplateData.Location),
|
||||
fmt.Sprintf("--template-uri %s", testTemplateData.TemplateURL),
|
||||
fmt.Sprintf("%s='%s'", armParamLocation, testTemplateData.Location),
|
||||
fmt.Sprintf("%s='%s'", armParamSignozAPIKey, testTemplateData.SignozAPIKey),
|
||||
fmt.Sprintf("%s='%s'", armParamSignozAPIUrl, testTemplateData.SignozAPIUrl),
|
||||
fmt.Sprintf("%s='%s'", armParamSignozIngestionURL, testTemplateData.SignozIngestionURL),
|
||||
fmt.Sprintf("%s='%s'", armParamSignozIngestionKey, testTemplateData.SignozIngestionKey),
|
||||
fmt.Sprintf("%s='%s'", armParamAccountID, testTemplateData.AccountID),
|
||||
fmt.Sprintf("%s='%s'", armParamAgentVersion, testTemplateData.AgentVersion),
|
||||
"--action-on-unmanage deleteAll",
|
||||
"--deny-settings-mode denyDelete",
|
||||
}
|
||||
|
||||
for _, fragment := range mustContain {
|
||||
if !strings.Contains(cmd, fragment) {
|
||||
t.Errorf("CLI command missing %q\ngot:\n%s", fragment, cmd)
|
||||
}
|
||||
}
|
||||
|
||||
// Lines must be joined with the bash line-continuation separator.
|
||||
if !strings.Contains(cmd, " \\\n") {
|
||||
t.Errorf("CLI command missing line-continuation separator ' \\\\\\n'\ngot:\n%s", cmd)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewAzureConnectionPowerShellCommand(t *testing.T) {
|
||||
cmd, err := newAzureConnectionPowerShellCommand(testTemplateData)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
mustContain := []string{
|
||||
"New-AzSubscriptionDeploymentStack",
|
||||
fmt.Sprintf("-Name \"%s\"", AgentDeploymentStackName),
|
||||
fmt.Sprintf("-Location \"%s\"", testTemplateData.Location),
|
||||
fmt.Sprintf("-TemplateUri \"%s\"", testTemplateData.TemplateURL),
|
||||
armParamLocation,
|
||||
armParamSignozAPIKey,
|
||||
armParamSignozAPIUrl,
|
||||
armParamSignozIngestionURL,
|
||||
armParamSignozIngestionKey,
|
||||
armParamAccountID,
|
||||
armParamAgentVersion,
|
||||
armParamRgName,
|
||||
armParamContainerEnvName,
|
||||
armParamDeploymentEnv,
|
||||
armDefaultRgName,
|
||||
armDefaultContainerEnvName,
|
||||
armDefaultDeploymentEnv,
|
||||
"-ActionOnUnmanage \"deleteAll\"",
|
||||
"-DenySettingsMode \"denyDelete\"",
|
||||
}
|
||||
|
||||
for _, fragment := range mustContain {
|
||||
if !strings.Contains(cmd, fragment) {
|
||||
t.Errorf("PowerShell command missing %q\ngot:\n%s", fragment, cmd)
|
||||
}
|
||||
}
|
||||
|
||||
// Final command must not end with a line-continuation backtick.
|
||||
if strings.HasSuffix(strings.TrimSpace(cmd), "`") {
|
||||
t.Errorf("PowerShell command must not end with a backtick\ngot:\n%s", cmd)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewAzureConnectionArtifact(t *testing.T) {
|
||||
accountID := valuer.GenerateUUID()
|
||||
agentVersion := "v0.1.0"
|
||||
creds := &Credentials{
|
||||
SigNozAPIURL: "https://signoz.example.com",
|
||||
SigNozAPIKey: "test-api-key",
|
||||
IngestionURL: "https://ingest.example.com",
|
||||
IngestionKey: "test-ingest-key",
|
||||
}
|
||||
cfg := &AzurePostableAccountConfig{
|
||||
DeploymentRegion: "eastus",
|
||||
ResourceGroups: []string{"rg1"},
|
||||
}
|
||||
|
||||
artifact, err := NewAzureConnectionArtifact(accountID, agentVersion, creds, cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if artifact.CLICommand == "" {
|
||||
t.Error("CLICommand must not be empty")
|
||||
}
|
||||
if artifact.CloudPowerShellCommand == "" {
|
||||
t.Error("CloudPowerShellCommand must not be empty")
|
||||
}
|
||||
if !strings.Contains(artifact.CLICommand, accountID.StringValue()) {
|
||||
t.Errorf("CLICommand must contain accountID %q", accountID.StringValue())
|
||||
}
|
||||
if !strings.Contains(artifact.CloudPowerShellCommand, accountID.StringValue()) {
|
||||
t.Errorf("CloudPowerShellCommand must contain accountID %q", accountID.StringValue())
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,13 @@ var (
|
||||
GCPConnectionMethodManual = GCPConnectionMethod{valuer.NewString("manual")}
|
||||
GCPConnectionMethodAgent = GCPConnectionMethod{valuer.NewString("agent")}
|
||||
|
||||
gcpCLITemplate = template.Must(template.New("gcpCLI").Funcs(foundryTemplateFuncs).Parse(gcpCLITemplateStr()))
|
||||
foundryScriptURL = "https://signoz.io/foundry.sh"
|
||||
|
||||
gcpCLITemplate = template.Must(template.New("gcpCLI").Funcs(template.FuncMap{
|
||||
"shellQuote": func(value string) string {
|
||||
return "'" + strings.ReplaceAll(value, "'", "'\"'\"'") + "'"
|
||||
},
|
||||
}).Parse(gcpCLITemplateStr()))
|
||||
)
|
||||
|
||||
type GCPConnectionMethod struct{ valuer.String }
|
||||
@@ -106,14 +112,12 @@ func (config *GCPAccountConfig) ErrIfInvalid() error {
|
||||
|
||||
func NewGCPConnectionArtifact(integrationAccountID valuer.UUID, agentVersion string, creds *Credentials, cfg *GCPAccountConfig) (*GCPConnectionArtifact, error) {
|
||||
data := gcpTemplateData{
|
||||
foundryTemplateData: foundryTemplateData{
|
||||
FoundryScriptURL: foundryScriptURL,
|
||||
Region: cfg.DeploymentRegion,
|
||||
IntegrationAccountID: integrationAccountID.StringValue(),
|
||||
AgentVersion: agentVersion,
|
||||
Credentials: creds,
|
||||
},
|
||||
ProjectID: cfg.DeploymentProjectID,
|
||||
FoundryScriptURL: foundryScriptURL,
|
||||
ProjectID: cfg.DeploymentProjectID,
|
||||
Region: cfg.DeploymentRegion,
|
||||
IntegrationAccountID: integrationAccountID.StringValue(),
|
||||
AgentVersion: agentVersion,
|
||||
Credentials: creds,
|
||||
}
|
||||
|
||||
var command bytes.Buffer
|
||||
@@ -154,8 +158,12 @@ func NewGCPIntegrationConfig(config *GCPAccountConfig, metricNames, sinkFilters
|
||||
}
|
||||
|
||||
type gcpTemplateData struct {
|
||||
foundryTemplateData
|
||||
ProjectID string
|
||||
FoundryScriptURL string
|
||||
ProjectID string
|
||||
Region string
|
||||
IntegrationAccountID string
|
||||
AgentVersion string
|
||||
Credentials *Credentials
|
||||
}
|
||||
|
||||
func gcpCLITemplateStr() string {
|
||||
|
||||
9
tests/e2e/drivers/channels.ts
generated
9
tests/e2e/drivers/channels.ts
generated
@@ -209,10 +209,6 @@ interface ChannelForm {
|
||||
/** Saves an existing channel and waits for the write to land. */
|
||||
saveEdit(): Promise<void>;
|
||||
save(): Promise<void>;
|
||||
/** The sticky bar holding discard, test and save. */
|
||||
actions(): Locator;
|
||||
/** Scrolls with the mouse wheel, which unlike scrollIntoView cannot move an overflow: hidden box. */
|
||||
wheelToEnd(): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -338,11 +334,6 @@ function channelsDriver(page: Page): Channels {
|
||||
async save() {
|
||||
await page.getByTestId('save-channel-button').click();
|
||||
},
|
||||
actions: () => page.getByTestId('discard-channel-button').locator('..'),
|
||||
async wheelToEnd() {
|
||||
await form.name().hover();
|
||||
await page.mouse.wheel(0, 10_000);
|
||||
},
|
||||
};
|
||||
|
||||
const api: ChannelApi = {
|
||||
|
||||
37
tests/e2e/drivers/integrations.ts
generated
37
tests/e2e/drivers/integrations.ts
generated
@@ -210,13 +210,15 @@ export interface AwsFlow {
|
||||
toggleRegion(code: string): Promise<void>;
|
||||
/** Fill whichever credential inputs the credentials endpoint left empty. */
|
||||
fillMissingCredentials(): Promise<void>;
|
||||
/** Submit the add-account drawer. Resolves the agent setup command it returned. */
|
||||
generateCommand(): Promise<{
|
||||
/**
|
||||
* Submit the add-account drawer. `window.open` is replaced first, so no AWS
|
||||
* console tab opens; the URL it was called with is returned instead.
|
||||
*/
|
||||
launch(): Promise<{
|
||||
accountId: string;
|
||||
command: string;
|
||||
connectionUrl: string;
|
||||
body: { config?: { aws?: { regions?: string[] } } };
|
||||
}>;
|
||||
agentCommand(): Locator;
|
||||
/** Set exactly `codes` in the edit drawer and press Update Changes. */
|
||||
updateRegions(codes: string[]): Promise<Response>;
|
||||
}
|
||||
@@ -490,23 +492,34 @@ export function cloudDriver(page: Page, provider: CloudProvider): Cloud {
|
||||
}
|
||||
},
|
||||
|
||||
generateCommand: async () => {
|
||||
launch: async () => {
|
||||
await page.evaluate(() => {
|
||||
const w = window as unknown as {
|
||||
open: (url?: string) => null;
|
||||
__e2eOpened?: string;
|
||||
};
|
||||
w.open = (url?: string): null => {
|
||||
w.__e2eOpened = String(url ?? '');
|
||||
return null;
|
||||
};
|
||||
});
|
||||
const created = page.waitForResponse(isCall('POST', `${base}/accounts`));
|
||||
await page.getByTestId('aws-generate-command-btn').click();
|
||||
await page.getByTestId('aws-launch-cfn-btn').click();
|
||||
const response = await created;
|
||||
expect(response.status(), await response.text()).toBe(201);
|
||||
const { data } = (await response.json()) as {
|
||||
data: { id: string; connectionArtifact: { aws: { cliCommand: string } } };
|
||||
};
|
||||
const { data } = (await response.json()) as { data: { id: string } };
|
||||
const connectionUrl = await page
|
||||
.waitForFunction(
|
||||
() => (window as unknown as { __e2eOpened?: string }).__e2eOpened,
|
||||
)
|
||||
.then((handle) => handle.jsonValue() as Promise<string>);
|
||||
return {
|
||||
accountId: data.id,
|
||||
command: data.connectionArtifact.aws.cliCommand,
|
||||
connectionUrl,
|
||||
body: response.request().postDataJSON(),
|
||||
};
|
||||
},
|
||||
|
||||
agentCommand: () => page.getByTestId('aws-agent-command'),
|
||||
|
||||
updateRegions: async (codes) => {
|
||||
const boxes = page.locator('[data-testid^="aws-region-"]');
|
||||
await expect(boxes.first()).toBeVisible();
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
import { type Page } from '@playwright/test';
|
||||
|
||||
import { type Channels, expect, test } from '../../../drivers/channels';
|
||||
|
||||
// Shorter than the Slack form, so it only fits by scrolling inside the
|
||||
// configuration pane, whose own overflow is hidden.
|
||||
test.use({ viewport: { width: 1280, height: 600 } });
|
||||
|
||||
async function expectScrollsWithActionsPinned(
|
||||
page: Page,
|
||||
form: Channels['form'],
|
||||
): Promise<void> {
|
||||
const actions = form.actions();
|
||||
const lastControl = page.getByTestId('slack-action-add');
|
||||
|
||||
await expect(actions).toBeInViewport({ ratio: 1 });
|
||||
await expect(lastControl).not.toBeInViewport();
|
||||
|
||||
await form.wheelToEnd();
|
||||
|
||||
await expect(lastControl).toBeInViewport({ ratio: 1 });
|
||||
await expect(actions).toBeInViewport({ ratio: 1 });
|
||||
|
||||
const control = await lastControl.boundingBox();
|
||||
const bar = await actions.boundingBox();
|
||||
expect(control!.y + control!.height).toBeLessThanOrEqual(bar!.y);
|
||||
}
|
||||
|
||||
test.describe('Notification channels — form scroll', () => {
|
||||
test('TC-01 the new channel form scrolls to its end with actions pinned', async ({
|
||||
channels,
|
||||
authedPage,
|
||||
}) => {
|
||||
await channels.form.gotoNew();
|
||||
await channels.form.pickType('Slack');
|
||||
await expect(authedPage.getByTestId('slack-action-add')).toBeAttached();
|
||||
|
||||
await expectScrollsWithActionsPinned(authedPage, channels.form);
|
||||
});
|
||||
|
||||
test('TC-02 the edit channel form scrolls to its end with actions pinned', async ({
|
||||
channels,
|
||||
authedPage,
|
||||
}) => {
|
||||
let id: string | undefined;
|
||||
|
||||
try {
|
||||
({ id } = await channels.api.create(`e2e-ncs-${Date.now()}`));
|
||||
await authedPage.goto(`/alerts/channels/edit/${id}`);
|
||||
await expect(channels.form.name()).toBeVisible();
|
||||
|
||||
await expectScrollsWithActionsPinned(authedPage, channels.form);
|
||||
} finally {
|
||||
await channels.api.remove(id);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -98,12 +98,15 @@ test.describe('Cloud integrations', () => {
|
||||
await aws.aws.toggleRegion('us-east-1');
|
||||
await aws.aws.fillMissingCredentials();
|
||||
|
||||
const generated = await aws.aws.generateCommand();
|
||||
accountId = generated.accountId;
|
||||
expect(generated.body.config?.aws?.regions).toEqual(['us-east-1']);
|
||||
expect(generated.command).toContain('cloudintegration aws cloudformation');
|
||||
expect(generated.command).toContain(accountId);
|
||||
await expect(aws.aws.agentCommand()).toContainText(accountId);
|
||||
const launched = await aws.aws.launch();
|
||||
accountId = launched.accountId;
|
||||
expect(launched.body.config?.aws?.regions).toEqual(['us-east-1']);
|
||||
expect(launched.connectionUrl).toContain(
|
||||
'console.aws.amazon.com/cloudformation',
|
||||
);
|
||||
expect(launched.connectionUrl).toContain(
|
||||
`param_SigNozAccountId=${accountId}`,
|
||||
);
|
||||
await expect(aws.waitingCallout()).toBeVisible();
|
||||
|
||||
await aws.checkIn(accountId, providerAccountId);
|
||||
|
||||
@@ -83,12 +83,11 @@ def test_create_account(
|
||||
|
||||
if spec.provider == "aws":
|
||||
assert "aws" in artifact, "connectionArtifact should contain 'aws' field"
|
||||
assert "cliCommand" in artifact["aws"], "connectionArtifact.aws should contain 'cliCommand'"
|
||||
assert "connectionUrl" in artifact["aws"], "connectionArtifact.aws should contain 'connectionUrl'"
|
||||
|
||||
cli_command = artifact["aws"]["cliCommand"]
|
||||
assert "cloudintegration aws cloudformation" in cli_command, "cliCommand should run the foundry aws cloudformation flow"
|
||||
assert f"--region '{spec.initial_params['deployment_region']}'" in cli_command, "cliCommand should contain the deployment region"
|
||||
assert f"--integration-account-id '{data['id']}'" in cli_command, "cliCommand should contain the integration account id"
|
||||
connection_url = artifact["aws"]["connectionUrl"]
|
||||
assert "console.aws.amazon.com/cloudformation" in connection_url, "connectionUrl should be an AWS CloudFormation URL"
|
||||
assert f"region={spec.initial_params['deployment_region']}" in connection_url, "connectionUrl should contain the deployment region"
|
||||
else:
|
||||
# GCP is a manual flow: no one-click install artifact.
|
||||
assert artifact.get("gcp") is None, f"GCP should not return a connection artifact, got: {artifact}"
|
||||
|
||||
Reference in New Issue
Block a user