### Sentry URL Examples Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/configuration.md Examples of Sentry URLs for SaaS and self-hosted instances. ```text https://sentry.io ``` ```text https://sentry.company.com ``` -------------------------------- ### Executed Query String Example Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/errors.md Shows an example of an executed query string that is included in frame metadata when an error occurs, aiding in debugging API calls to Sentry. ```http /api/0/organizations/my-org/issues/? query=is:unresolved &project=123 &start=2024-01-01T00:00:00 &end=2024-01-31T23:59:59 ``` -------------------------------- ### Sentry Organization Slug Example Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/configuration.md Example of a Sentry organization slug, visible in the organization settings URL. ```text https://sentry.io/organizations/{orgSlug}/ ``` -------------------------------- ### GetIssues Method Example Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryClientAPI.md Fetches issues from Sentry using specified filters and sorting. Requires a configured SentryClient instance. ```go issues, url, err := client.GetIssues(sentry.GetIssuesInput{ OrganizationSlug: "my-org", ProjectIds: []string{"123"}, Environments: []string{"production"}, Query: "is:unresolved level:error", From: time.Now().Add(-7 * 24 * time.Hour), To: time.Now(), Sort: "date", Limit: 100, }) ``` -------------------------------- ### Error Logging Examples Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/errors.md Provides examples of how backend errors are logged to Grafana logs, including details about the query and the specific error message. ```text [error] SentryDatasource: Query failed for org "my-org" [error] SentryDatasource: QueryType=issues, Error="Invalid token" ``` -------------------------------- ### FetchWithPagination() - HTTP GET with Pagination Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryClientAPI.md Executes an HTTP GET request with pagination support. Returns the URL for the next page of results if available. Useful for retrieving large datasets. ```go func (sc *SentryClient) FetchWithPagination(path string, out interface{}) (string, error) ``` -------------------------------- ### Example: Team Variable Configuration Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryVariableEditor.md Configuration for a Grafana dashboard variable named 'team' that lists all Sentry teams. ```text Variable name: team Label: Team Variable type: Query Datasource: Sentry Query: { "type": "teams" } ``` -------------------------------- ### Grafana Provisioning Configuration (SaaS) Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/configuration.md Example of configuring the Sentry datasource via Grafana provisioning YAML for a SaaS instance. ```yaml apiVersion: 1 datasources: - name: Sentry type: grafana-sentry-datasource access: proxy orgId: 1 version: 1 editable: false jsonData: url: https://sentry.io orgSlug: my-org secureJsonData: authToken: sntrys_eyJ... ``` -------------------------------- ### Example: Environment Variable Configuration Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryVariableEditor.md Configuration for a Grafana dashboard variable named 'environment' that lists available environments from selected projects. ```text Variable name: environment Label: Environment Variable type: Query Datasource: Sentry Query: { "type": "environments", "projectIds": ["$project"] } ``` -------------------------------- ### Fetch() - Low-level HTTP GET Request Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryClientAPI.md Performs a low-level HTTP GET request to the Sentry API. Handles authentication and error responses. Use for direct API path access. ```go func (sc *SentryClient) Fetch(path string, out interface{}) error ``` -------------------------------- ### Example: Project Variable with Team Filter Configuration Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryVariableEditor.md Configuration for a cascading Grafana dashboard variable named 'project' that lists projects filtered by a selected team. ```text Variable name: project Label: Project Variable type: Query Datasource: Sentry Query: { "type": "projects", "teamSlug": "$team" } ``` -------------------------------- ### Sentry API Response (200 OK) - Projects Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/endpoints.md Example JSON response for a successful request to list projects for a team. ```JSON [ { "id": "456", "name": "API Service", "slug": "api-service", "environments": ["production", "staging"], "team": { ... }, "teams": [ ... ] } ] ``` -------------------------------- ### FetchWithPagination Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryClientAPI.md HTTP GET request with pagination support. Returns the next page URL if available. ```APIDOC ## FetchWithPagination(path string, out interface{}) ### Description HTTP GET request with pagination support. Returns the next page URL if available. ### Parameters #### Path Parameters - **path** (string) - Required - API path. - **out** (interface{}) - Required - Pointer to struct to unmarshal response ### Returns - **string** - Next page URL (empty if no more pages) - **error** - API error ``` -------------------------------- ### Example: Using Team Variable in Panel Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryVariableEditor.md How to use the 'team' dashboard variable to filter data in a Grafana panel. ```text Environment: $team ``` -------------------------------- ### Grafana Provisioning Configuration (Self-Hosted) Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/configuration.md Example of configuring the Sentry datasource via Grafana provisioning YAML for a self-hosted instance with TLS verification skipped. ```yaml apiVersion: 1 datasources: - name: Sentry Internal type: grafana-sentry-datasource access: proxy orgId: 1 version: 1 jsonData: url: https://sentry.internal.company.com orgSlug: internal-team tlsSkipVerify: true # For self-signed certificates secureJsonData: authToken: sntrys_internal_token_here ``` -------------------------------- ### Sentry API Response (501 Not Implemented) Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/endpoints.md Example response for unmatched API paths, indicating a 'Not Implemented' status. ```HTTP HTTP/1.1 501 Not Implemented not a valid resource call ``` -------------------------------- ### Multi-Project Environment Listing Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/UtilityFunctions.md Demonstrates how to get a list of unique environments across multiple selected Sentry projects. This is useful for applying filters to queries that span several projects. ```typescript // Get unique environments across multiple selected projects const selectedProjects = ['123', '456']; const uniqueEnvs = getEnvironmentNamesFromProject(projects, selectedProjects); // Returns: unique environments from both projects // Useful for filtering queries across multiple projects ``` -------------------------------- ### Configure Sentry Data Source via Provisioning Source: https://github.com/grafana/sentry-datasource/blob/main/README.md Example configuration for the Sentry data source using Grafana's provisioning system. Ensure to replace placeholder values with your actual Sentry organization slug and auth token. ```yaml apiVersion: 1 datasources: - name: Sentry type: grafana-sentry-datasource access: proxy orgId: 1 version: 1 editable: false jsonData: url: https://sentry.io orgSlug: xxxxxxxxxxxxx secureJsonData: authToken: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ``` -------------------------------- ### Handle Invalid Sentry Configuration Error Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/errors.md Example of how to check for and handle an invalid Sentry configuration error using errors.Is(). ```go if err := sc.Validate(); err != nil { if errors.Is(err, errors.ErrorInvalidSentryConfig) { // Handle invalid configuration log.Error("Sentry config is invalid") } } ``` -------------------------------- ### Downstream Error Example Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/errors.md Illustrates a downstream error originating from the Sentry API, such as an authentication failure. ```text Sentry API returns: 401 Unauthorized "Invalid token" → ErrorSourceDownstream ``` -------------------------------- ### Fetch Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryClientAPI.md Low-level HTTP GET request to Sentry API. Handles authentication and error responses. ```APIDOC ## Fetch(path string, out interface{}) ### Description Low-level HTTP GET request to Sentry API. Handles authentication and error responses. ### Parameters #### Path Parameters - **path** (string) - Required - API path (e.g., "/api/0/organizations/my-org/projects") - **out** (interface{}) - Required - Pointer to struct to unmarshal response ### Returns - **error** - API error or parsing error ``` -------------------------------- ### Pagination Link Header Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/endpoints.md Example of a 'Link' header in an API response, indicating the URL for the next page of results. ```HTTP Link: ; rel="next"; results="true" ``` -------------------------------- ### Health Check Response (OK) Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/endpoints.md Example JSON response for a successful health check, indicating the status and a message about found projects. ```JSON { "status": "ok", "message": "Successful health check. 5 projects found." } ``` -------------------------------- ### Multi-Project Filter with CSV Template Variable Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/TemplateVariableHandling.md This example demonstrates filtering Sentry events by multiple projects using a multi-select dashboard variable formatted as CSV. The `$projects:csv` syntax is used for this purpose. ```typescript const query: SentryEventsQuery = { queryType: 'events', projectIds: ['$projects:csv'], // Multi-select variable environments: ['$env'], eventsQuery: 'level:$severity', }; ``` -------------------------------- ### GET /api/0/organizations/{organization_slug}/projects Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/endpoints.md Lists all projects within a specified organization. This is useful for filtering data by project. ```APIDOC ## GET /api/0/organizations/{organization_slug}/projects ### Description Lists all projects in an organization. ### Method GET ### Endpoint /api/0/organizations/{organization_slug}/projects ### Parameters #### Path Parameters - **organization_slug** (string) - Required - Organization slug ### Request Example ``` GET /api/0/organizations/my-org/projects Authorization: Bearer {authToken} ``` ### Response #### Success Response (200 OK) - **id** (string) - Project ID - **name** (string) - Project name - **slug** (string) - Project slug - **environments** (array of strings) - List of environments associated with the project - **team** (object) - Primary team associated with the project - **id** (string) - Team ID - **name** (string) - Team name - **slug** (string) - Team slug - **teams** (array of objects) - List of teams associated with the project - **id** (string) - Team ID - **name** (string) - Team name - **slug** (string) - Team slug #### Response Example ```json [ { "id": "123", "name": "Frontend App", "slug": "frontend-app", "environments": ["production", "staging", "development"], "team": { "id": "team-1", "name": "Frontend Team", "slug": "frontend-team" }, "teams": [ { "id": "team-1", "name": "Frontend Team", "slug": "frontend-team" } ] } ] ``` #### Error Response (400 Bad Request) - **detail** (string) - Error message (e.g., "invalid orgSlug") #### Error Response (404 Not Found) - **detail** (string) - Error message (e.g., "The requested resource does not exist") ``` -------------------------------- ### Dashboard Variable for Environment Filter Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/UtilityFunctions.md Example of using `getEnvironmentNamesFromProject` to populate environment options for a dashboard dropdown filter. This is used when a user selects specific projects. ```typescript // User selects a project in the dashboard // Variable query: { type: 'environments', projectIds: ['123'] } // Plugin fetches projects, then calls: const envs = getEnvironmentNamesFromProject(projects, ['123']); // Returns options for dropdown: ['production', 'staging', 'development'] ``` -------------------------------- ### Sentry API Response (400 Bad Request) - Projects Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/endpoints.md Example JSON response for a bad request when listing projects, indicating invalid organization or team slugs. ```JSON { "detail": "invalid orgSlug or teamSlug" } ``` -------------------------------- ### Query Data Response Body Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/endpoints.md Example JSON response from the QueryData handler, containing results organized by reference ID and including frame data. ```JSON { "results": { "A": { "status": 200, "frames": [ { "refId": "A", "fields": [ ... ], "meta": { "executedQueryString": "...", "sentryURL": "...", "orgSlug": "..." } } ] } } } ``` -------------------------------- ### NewSentryClient Constructor Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryClientAPI.md Creates a new SentryClient instance. Requires Sentry base URL, organization slug, authentication token, and an HTTP client implementation. ```go func NewSentryClient(baseURL string, orgSlug string, authToken string, doerClient doer) (*SentryClient, error) ``` ```go client, err := sentry.NewSentryClient( "https://sentry.io", "my-org", "token123...", httpClient, ) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Build and Development Commands Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/PluginModule.md Run these npm scripts for building, development, linting, and type checking the plugin. The production build output is `dist/module.js`. ```bash npm run build # Production build npm run dev # Development watch npm run lint # ESLint check npm run typecheck # TypeScript check ``` -------------------------------- ### Development Build Commands Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/OVERVIEW.md Common commands for managing dependencies, building the project for production or development, linting, type checking, and running tests. ```bash npm install # Install dependencies npm run build # Production build npm run dev # Development watch npm run lint # Lint code npm run typecheck # Type check npm run test # Run tests ``` -------------------------------- ### GetProjects Function Signature Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryClientAPI.md Fetches all projects within an organization. Supports pagination for large result sets. ```go func (sc *SentryClient) GetProjects(organizationSlug string, withPagination bool) ([]SentryProject, error) ``` -------------------------------- ### CheckHealth Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryDatasourceBackend.md Verifies the datasource connection and configuration. This method is invoked by Grafana during setup and periodically for monitoring. ```APIDOC ## CheckHealth() ### Description Verifies the datasource connection and configuration. Called by Grafana during datasource setup and periodically for monitoring. ### Signature ```go func (ds *SentryDatasource) CheckHealth(ctx context.Context, req *backend.CheckHealthRequest) (*backend.CheckHealthResult, error) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Returns - `*backend.CheckHealthResult`: Health status and message - `error`: Should return nil (errors are handled as unhealthy status) ### Status Values - `backend.HealthStatusOk`: Connection successful - `backend.HealthStatusError`: Connection failed ### Health Check Procedure 1. Calls `client.GetProjects(orgSlug)` to verify API access 2. Returns OK if projects are retrieved 3. Returns error message if API call fails ### Example Response ```go &backend.CheckHealthResult{ Status: backend.HealthStatusOk, Message: "Successful health check. 5 projects found.", } ``` ``` -------------------------------- ### Query Execution Flow Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/OVERVIEW.md Illustrates the step-by-step process from user query initiation in a Grafana dashboard to data visualization, detailing backend and frontend interactions with the Sentry API. ```text 1. User runs query in dashboard ↓ 2. Grafana calls SentryDataSource.query() ↓ 3. Frontend applies template variables via applyTemplateVariables() ↓ 4. Query is sent to backend via HTTP ↓ 5. Backend SentryDatasource.QueryData() routes to handler ↓ 6. Handler validates org slug and parameters ↓ 7. SentryClient method calls Sentry API ↓ 8. Response is converted to Grafana DataFrame ↓ 9. FrameMeta is added with executed query string ↓ 10. DataFrame is returned to frontend ↓ 11. Panel visualizes the data ``` -------------------------------- ### All Available Environments Listing Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/UtilityFunctions.md Shows how to retrieve all unique environment names across all available Sentry projects when no specific projects are selected. This provides a comprehensive list for organizational-level filtering. ```typescript // When user hasn't selected specific projects, show all available const allEnvs = getEnvironmentNamesFromProject(projects, []); // Returns: every unique environment name across the organization ``` -------------------------------- ### GET /api/0/organizations/{organization_slug}/teams Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/endpoints.md Lists all teams within a specified organization. This can be used for team-based filtering or display. ```APIDOC ## GET /api/0/organizations/{organization_slug}/teams ### Description Lists all teams in an organization. ### Method GET ### Endpoint /api/0/organizations/{organization_slug}/teams ### Parameters #### Path Parameters - **organization_slug** (string) - Required - Organization slug ### Request Example ``` GET /api/0/organizations/my-org/teams Authorization: Bearer {authToken} ``` ### Response #### Success Response (200 OK) - **id** (string) - Team ID - **name** (string) - Team name - **slug** (string) - Team slug - **hasAccess** (boolean) - Indicates if the user has access to the team - **isMember** (boolean) - Indicates if the user is a member of the team - **dateCreated** (string) - ISO 8601 formatted date of creation #### Response Example ```json [ { "id": "team-123", "name": "Backend Team", "slug": "backend-team", "hasAccess": true, "isMember": true, "dateCreated": "2023-02-10T08:15:00Z" } ] ``` ``` -------------------------------- ### Get Sentry Organization Slug Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryDataSource.md Retrieves the organization slug from the datasource configuration. Returns an empty string if not configured. ```typescript const orgSlug = datasource.getOrgSlug(); console.log(orgSlug); // 'my-org' ``` -------------------------------- ### NewDatasourceInstance Constructor Function Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryDatasourceBackend.md Creates a Sentry datasource instance from an existing Sentry client. This is primarily used for testing purposes. ```go func NewDatasourceInstance(sc *sentry.SentryClient) *SentryDatasource ``` ```go client, _ := sentry.NewSentryClient("https://sentry.io", "my-org", "token", httpClient) ds := NewDatasourceInstance(client) ``` -------------------------------- ### NewDatasource Constructor Function Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryDatasourceBackend.md Creates a new Sentry datasource instance. It parses settings, initializes the HTTP client and Sentry client, and sets up the resource router. This function is called by Grafana's datasource management system. ```go func NewDatasource(ctx context.Context, s backend.DataSourceInstanceSettings) (instancemgmt.Instance, error) ``` ```go settings := backend.DataSourceInstanceSettings{ JSONData: []byte(`{ "url": "https://sentry.io", "orgSlug": "my-org" }`), DecryptedSecureJSONData: map[string]string{ "authToken": "token123...", }, } instance, err := NewDatasource(ctx, settings) ``` -------------------------------- ### GET /api/0/organizations Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/endpoints.md Lists all organizations the authenticated user has access to. This endpoint is useful for populating organization selection dropdowns in the UI. ```APIDOC ## GET /api/0/organizations ### Description Lists all organizations the authenticated user has access to. ### Method GET ### Endpoint /api/0/organizations ### Parameters ### Request Example ``` GET /api/0/organizations Authorization: Bearer {authToken} ``` ### Response #### Success Response (200 OK) - **id** (string) - Organization ID - **name** (string) - Organization name - **slug** (string) - Organization slug - **dateCreated** (string) - ISO 8601 formatted date of creation - **status** (object) - Current status of the organization - **id** (string) - Status ID (e.g., "active") - **name** (string) - Status name (e.g., "Active") #### Response Example ```json [ { "id": "org-id-123", "name": "My Organization", "slug": "my-org", "dateCreated": "2023-01-15T10:30:00Z", "status": { "id": "active", "name": "Active" } } ] ``` #### Error Response (401 Unauthorized) - **detail** (string) - Error message (e.g., "Invalid token") #### Error Response (403 Forbidden) - **detail** (string) - Error message (e.g., "User does not have permission") ``` -------------------------------- ### NewSentryClient() Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryClientAPI.md Creates a new SentryClient instance used for making API calls to Sentry. It requires the Sentry base URL, organization slug, an authentication token, and an HTTP client implementation. ```APIDOC ## NewSentryClient() ### Description Creates a new SentryClient instance. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Returns - `*SentryClient` - New client instance - `error` - Error during client creation ### Example ```go client, err := sentry.NewSentryClient( "https://sentry.io", "my-org", "token123...", httpClient, ) if err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Successful Health Check Message Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/configuration.md Example success message returned by the datasource health check upon successful API connectivity. ```text "Successful health check. X projects found." ``` -------------------------------- ### Grafana Sentry Datasource Architecture Diagram Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/OVERVIEW.md Illustrates the client-server architecture of the Grafana Sentry datasource plugin, showing interactions between Grafana Frontend, Grafana Backend, and the Sentry API. ```text ┌─────────────────────────────────────────────────────────────┐ │ Grafana Frontend │ ├─────────────────────────────────────────────────────────────┤ │ SentryDataSource (TypeScript) │ │ ├── SentryQueryEditor (React) │ │ ├── SentryConfigEditor (React) │ │ ├── SentryVariableEditor (React) │ │ └── TemplateVariableHandling │ └──────────────────────────┬──────────────────────────────────┘ │ JSON over HTTP ┌──────────────────────────┴──────────────────────────────────┐ │ Grafana Backend │ ├─────────────────────────────────────────────────────────────┤ │ SentryDatasource (Go) │ │ ├── QueryData Handler │ │ ├── CheckHealth Handler │ │ ├── Resource Router │ │ └── SentryClient (API calls to Sentry) │ └──────────────────────────┬──────────────────────────────────┘ │ HTTPS API calls ┌──────────────────────────┴──────────────────────────────────┐ │ Sentry API │ │ (https://sentry.io or self-hosted) │ └─────────────────────────────────────────────────────────────┘ ``` -------------------------------- ### GetProjects() Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryClientAPI.md Fetches all projects in an organization. Supports pagination for large result sets. ```APIDOC ## GetProjects() ### Description Fetches all projects within a specified organization. Can enable pagination for handling large numbers of projects. ### Method (Not specified, likely a client SDK method) ### Endpoint (Not specified) ### Parameters - **organizationSlug** (string) - Required - The slug of the organization. - **withPagination** (bool) - Optional - Enable pagination for large result sets. ### Returns - `[]SentryProject` - An array of Sentry projects. - `error` - Query error. ``` -------------------------------- ### List Projects in an Organization Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/endpoints.md Lists all projects within a specified organization. Requires the organization slug as a path parameter. ```http GET /api/0/organizations/my-org/projects Authorization: Bearer {authToken} ``` -------------------------------- ### Health Check Response (Error) Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/endpoints.md Example JSON response for a failed health check, indicating an error status and a message about invalid credentials. ```JSON { "status": "error", "message": "Invalid token or organization" } ``` -------------------------------- ### Using Template Variables in Sentry Queries Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryVariableEditor.md Examples of how Grafana template variables can be interpolated within Sentry queries for filtering issues and data. ```text projectIds: ["$project"] environments: ["$environment"] issuesQuery: "team:$team is:unresolved" ``` -------------------------------- ### Sentry Backend Settings Structure (Go) Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/configuration.md Defines the structure for Sentry datasource configuration in Go, including fields for URL, organization slug, TLS skip verification, and auth token. ```go type SentryConfig struct { URL string `json:"url"` OrgSlug string `json:"orgSlug"` TLSSkipVerify bool `json:"tlsSkipVerify"` authToken string `json:"-"` // Populated from secureJsonData } ``` -------------------------------- ### NewDatasourceInstance Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryDatasourceBackend.md Creates a Sentry datasource instance from an existing Sentry client. This is primarily intended for testing purposes. ```APIDOC ## NewDatasourceInstance() ### Description Creates a datasource instance from an existing Sentry client. Primarily used for testing. ### Signature ```go func NewDatasourceInstance(sc *sentry.SentryClient) *SentryDatasource ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Returns - `*SentryDatasource`: New datasource instance ### Example ```go client, _ := sentry.NewSentryClient("https://sentry.io", "my-org", "token", httpClient) ds := NewDatasourceInstance(client) ``` ``` -------------------------------- ### GET /api/0/organizations/{organization_slug}/trace-items/attributes Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/endpoints.md Lists available trace item attributes for span queries. Used by the spans query editor to suggest attribute names. ```APIDOC ## GET /api/0/organizations/{organization_slug}/trace-items/attributes ### Description Lists available trace item attributes for span queries. Used by the spans query editor to suggest attribute names for span queries. ### Method GET ### Endpoint /api/0/organizations/{organization_slug}/trace-items/attributes ### Parameters #### Path Parameters - **organization_slug** (string) - Required - Organization slug ### Request Example ``` GET /api/0/organizations/my-org/trace-items/attributes Authorization: Bearer {authToken} ``` ### Response #### Success Response (200 OK) - **key** (string) - The attribute key (e.g., "span.op") - **name** (string) - The display name of the attribute (e.g., "Operation") #### Response Example ```json [ { "key": "span.op", "name": "Operation" }, { "key": "span.description", "name": "Description" }, { "key": "span.duration", "name": "Duration" } ] ``` ``` -------------------------------- ### GetOrganizations Function Signature Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryClientAPI.md Retrieves a list of all organizations accessible by the authenticated user. ```go func (sc *SentryClient) GetOrganizations() ([]SentryOrganization, error) ``` -------------------------------- ### GET /api/0/organizations/{organization_slug}/tags Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/endpoints.md Lists available tags (event attribute keys) in an organization. Used by the events query editor to suggest tag names. ```APIDOC ## GET /api/0/organizations/{organization_slug}/tags ### Description Lists available tags (event attribute keys) in an organization. Used by the events query editor to suggest tag names for filter queries. ### Method GET ### Endpoint /api/0/organizations/{organization_slug}/tags ### Parameters #### Path Parameters - **organization_slug** (string) - Required - Organization slug ### Request Example ``` GET /api/0/organizations/my-org/tags Authorization: Bearer {authToken} ``` ### Response #### Success Response (200 OK) - **key** (string) - The tag key (e.g., "environment") - **name** (string) - The display name of the tag (e.g., "Environment") - **totalValues** (integer) - The total number of unique values for this tag in the organization #### Response Example ```json [ { "key": "environment", "name": "Environment", "totalValues": 5 }, { "key": "level", "name": "Level", "totalValues": 4 }, { "key": "os.name", "name": "OS Name", "totalValues": 8 } ] ``` ``` -------------------------------- ### Instantiate SentryDataSource Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryDataSource.md Creates a new instance of the SentryDataSource. Requires Grafana datasource instance configuration. ```typescript const datasource = new SentryDataSource(instanceSettings); ``` -------------------------------- ### Grafana Sentry Datasource Project Structure Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/OVERVIEW.md Details the directory structure of the Grafana Sentry datasource plugin, outlining the organization of frontend (TypeScript/React) and backend (Go) code. ```text sentry-datasource/ ├── src/ # Frontend TypeScript/React │ ├── module.ts # Plugin entry point │ ├── datasource.ts # Main SentryDataSource class │ ├── types.ts # TypeScript type definitions │ ├── constants.ts # UI constants and options │ ├── editors/ # Grafana editor components │ │ ├── SentryConfigEditor.tsx │ │ ├── SentryQueryEditor.tsx │ │ └── SentryVariableEditor.tsx │ ├── components/ # UI components │ │ ├── query-editor/ # Query type editors │ │ ├── config-editor/ # Config components │ │ ├── variable-query-editor/# Variable editors │ │ └── Error.tsx │ ├── app/ # Business logic │ │ ├── replace.ts # Template variable handling │ │ └── utils.ts # Utility functions │ └── styles.ts │ ├── pkg/ # Backend Go code │ ├── main.go # Entry point │ ├── plugin/ │ │ ├── plugin.go # Main plugin handler │ │ ├── router.go # API route definitions │ │ └── settings.go # Configuration parsing │ ├── sentry/ # Sentry API client │ │ ├── sentry.go # Core client │ │ ├── client.go # HTTP client wrapper │ │ ├── issues.go # Issues API │ │ ├── events.go # Events API │ │ ├── events_stats.go # Events stats API │ │ ├── spans.go # Spans API │ │ ├── spans_stats.go # Spans stats API │ │ ├── metrics.go # Metrics API │ │ ├── stats_v2.go # Stats V2 API │ │ ├── projects.go # Projects API │ │ ├── team.go # Teams API │ │ ├── tags.go # Tags API │ │ ├── attributes.go # Attributes API │ │ └── orgs.go # Organizations API │ ├── handlers/ # Query handlers │ │ └── handlers.go # Handler implementations │ ├── query/ # Query models │ │ ├── model.go # Query struct │ │ └── helpers.go │ ├── framer/ # Data frame conversion │ │ ├── framer.go │ │ └── converters.go │ ├── errors/ # Error types │ │ └── errors.go │ └── util/ # Utilities │ └── config/ # Build configuration ├── webpack/ # Webpack config └── jest/ # Jest test config ``` -------------------------------- ### ListOrganizationTeams Function Signature Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryClientAPI.md Fetches all teams belonging to a specific organization. Supports pagination. ```go func (sc *SentryClient) ListOrganizationTeams(organizationSlug string, withPagination bool) ([]SentryTeam, error) ``` -------------------------------- ### SentryClient Struct Definition Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryClientAPI.md Defines the structure of the SentryClient, which holds configuration and the HTTP client for interacting with the Sentry API. ```go type SentryClient struct { BaseURL string OrgSlug string authToken string sentryHttpClient HTTPClient } ``` -------------------------------- ### Import Plugin Version Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/PluginModule.md Imports the plugin version from the package.json file, which is used for User-Agent headers, analytics tracking, and plugin identification. ```typescript import sentryVersion from '../package.json'; // sentryVersion.version = "2.2.5" (or current version) ``` -------------------------------- ### GetOrganizations() Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryClientAPI.md Fetches all organizations that the authenticated user has access to. ```APIDOC ## GetOrganizations() ### Description Fetches a list of all organizations that the currently authenticated user has access to. ### Method (Not specified, likely a client SDK method) ### Endpoint (Not specified) ### Returns - `[]SentryOrganization` - An array of Sentry organizations. ``` -------------------------------- ### CheckHealth Method Implementation Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryDatasourceBackend.md Verifies the datasource connection and configuration by calling the Sentry client's GetProjects method. Returns a health status and message indicating success or failure. ```go func (ds *SentryDatasource) CheckHealth(ctx context.Context, req *backend.CheckHealthRequest) (*backend.CheckHealthResult, error) ``` ```go &backend.CheckHealthResult{ Status: backend.HealthStatusOk, Message: "Successful health check. 5 projects found.", } ``` -------------------------------- ### getProjects Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryDataSource.md Fetches all projects in the specified organization. This method requires an organization slug and returns a promise that resolves to an array of SentryProject objects. ```APIDOC ## getProjects(orgSlug: string) ### Description Fetches all projects in the specified organization. ### Method `getProjects` ### Parameters #### Path Parameters - **orgSlug** (string) - Required - Organization slug ### Returns `Promise` - Array of project objects ### Request Example ```typescript datasource.getProjects('my-org').then(projects => { projects.forEach(p => console.log(p.name, p.id)); }); ``` ``` -------------------------------- ### Sentry Datasource File Organization Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/INDEX.md Provides a directory structure overview for the Sentry datasource plugin, categorizing files by their purpose. ```text output/ ├── INDEX.md # This file ├── OVERVIEW.md # Architecture overview ├── types.md # Type definitions ├── endpoints.md # API endpoints ├── configuration.md # Configuration reference ├── errors.md # Error types └── api-reference/ # API documentation ├── SentryDataSource.md # Frontend datasource ├── SentryDatasourceBackend.md # Backend handler ├── SentryClientAPI.md # API client ├── SentryConfigEditor.md # Config editor ├── SentryQueryEditor.md # Query editor ├── SentryVariableEditor.md # Variable editor ├── PluginModule.md # Plugin entry point ├── TemplateVariableHandling.md # Variable functions └── UtilityFunctions.md # Helper functions ``` -------------------------------- ### GetStatsV2 Function Signature Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryClientAPI.md Fetches organization statistics for quota and data tracking, supporting various filtering and grouping options. ```go func (sc *SentryClient) GetStatsV2(args GetStatsV2Input) (StatsV2Response, string, error) ``` -------------------------------- ### GetTags() - Fetch Organization Tags Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryClientAPI.md Fetches available tags (event attributes) in an organization. Use this to retrieve key-value pairs associated with events. ```go func (sc *SentryClient) GetTags(organizationSlug string, withPagination bool) ([]SentryTag, error) ``` ```go type SentryTag struct { Key string Name string TotalValues int } ``` -------------------------------- ### GetIssues() Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryClientAPI.md Fetches issues from Sentry, allowing for filtering by project, environment, query string, time range, and sorting. It returns an array of Sentry issues, the full query URL, and any potential errors. ```APIDOC ## GetIssues() ### Description Fetches issues from Sentry with filtering and sorting. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body **Input Type:** `GetIssuesInput` | Field | Type | Description | |-------|------|-------------| | OrganizationSlug | string | Required - Organization slug | | ProjectIds | []string | Optional - Project IDs to include | | Environments | []string | Optional - Environments to include | | Query | string | Optional - Sentry query string (e.g., "is:unresolved") | | From | time.Time | Required - Start of time range | | To | time.Time | Required - End of time range | | Sort | string | Optional - Sort field (date, new, priority, freq, user) | | Limit | int64 | Optional - Max results (default 10000) | ### Returns - `[]SentryIssue` - Array of issues - `string` - Full executed query URL - `error` - Query error ### Example ```go issues, url, err := client.GetIssues(sentry.GetIssuesInput{ OrganizationSlug: "my-org", ProjectIds: []string{"123"}, Environments: []string{"production"}, Query: "is:unresolved level:error", From: time.Now().Add(-7 * 24 * time.Hour), To: time.Now(), Sort: "date", Limit: 100, }) ``` ``` -------------------------------- ### GetTeamsProjects Function Signature Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryClientAPI.md Fetches projects specifically assigned to a given team within an organization. ```go func (sc *SentryClient) GetTeamsProjects(organizationSlug string, teamSlug string) ([]SentryProject, error) ``` -------------------------------- ### query() Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryDataSource.md Executes one or more Sentry queries based on the provided request, which includes targets, time range, and interval. It returns an Observable that emits the query results. ```APIDOC ## query() ### Description Executes one or more queries and returns the results as an Observable. ### Method `query` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **request** (`DataQueryRequest`) - Required - Query request containing targets, time range, and interval ### Request Example ```typescript const request = { targets: [ { refId: 'A', queryType: 'issues', projectIds: ['123'], environments: [], issuesQuery: 'is:unresolved', } ], range: { from: Date.now() - 7 * 24 * 60 * 60 * 1000, to: Date.now() } }; datasource.query(request).subscribe(response => { console.log(response.data); }); ``` ### Response #### Success Response (200) - **data** (`any`) - Query results #### Response Example ```json { "data": [ // ... query results ... ] } ``` ``` -------------------------------- ### State Management with React Hooks Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryConfigEditor.md Illustrates the use of React's useState hook to manage the local state for URL, organization slug, and authentication token within the SentryConfigEditor component. ```typescript const [url, setURL] = useState(jsonData?.url || DEFAULT_SENTRY_URL); const [orgSlug, setOrgSlug] = useState(jsonData?.orgSlug || ''); const [authToken, setAuthToken] = useState(''); ``` -------------------------------- ### QueryData Method Implementation Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryDatasourceBackend.md Handles data queries from Grafana by routing each query to the appropriate handler based on its 'queryType'. Supports various query types like 'issues', 'events', 'spans', and statistics. ```go func (ds *SentryDatasource) QueryData(ctx context.Context, req *backend.QueryDataRequest) (*backend.QueryDataResponse, error) ``` ```go req := &backend.QueryDataRequest{ Queries: []backend.DataQuery{ { RefID: "A", JSON: []byte(`{ "queryType": "issues", "projectIds": ["123"], "issuesQuery": "is:unresolved" }`), }, }, } response, err := ds.QueryData(ctx, req) // response.Responses["A"] contains the issues data ``` -------------------------------- ### GetMetrics Function Signature Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryClientAPI.md Fetches session health metrics for an organization. ```go func (sc *SentryClient) GetMetrics(args GetMetricsInput) (MetricsResponse, string, error) ``` -------------------------------- ### Main Plugin Export Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/PluginModule.md Exports the main plugin instance, which is the entry point that Grafana's plugin system discovers and uses to instantiate the plugin. ```typescript export const plugin ``` -------------------------------- ### Dispose Method Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryDatasourceBackend.md The Dispose method is called when the datasource instance is being disposed. It is currently a no-operation. ```go func (ds *SentryDatasource) Dispose() ``` -------------------------------- ### GetStatsV2 Input Type Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryClientAPI.md Defines the structure for fetching organization statistics, including categories, fields, and grouping for quota and data tracking. ```go type GetStatsV2Input struct { OrganizationSlug string From time.Time To time.Time Interval string Category []string Fields []string GroupBy []string ProjectIds []string Outcome []string Reason []string } ``` -------------------------------- ### GetStatsV2() Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryClientAPI.md Fetches organization statistics for quota and data tracking. Supports filtering by category, outcome, and reason. ```APIDOC ## GetStatsV2() ### Description Fetches organization statistics for quota and data tracking. Allows filtering by data categories, outcomes, and reasons, with specified time intervals and fields. ### Method (Not specified, likely a client SDK method) ### Endpoint (Not specified) ### Parameters #### Input Type: GetStatsV2Input - **OrganizationSlug** (string) - Required - The slug of the organization. - **From** (time.Time) - Optional - Start of the time range. - **To** (time.Time) - Optional - End of the time range. - **Interval** (string) - Required - Time interval (e.g., "1h", "1d") - format: [number][mhdw]. - **Category** ([]string) - Required - Data categories (error, transaction, attachment, session, security). - **Fields** ([]string) - Required - Fields (e.g., sum(quantity), sum(times_seen)). - **GroupBy** ([]string) - Optional - Group by (e.g., outcome, reason, category). - **ProjectIds** ([]string) - Optional - List of project IDs to filter by. - **Outcome** ([]string) - Optional - Outcomes (e.g., accepted, filtered, invalid, rate_limited, client_discard, abuse). - **Reason** ([]string) - Optional - Specific reasons to filter. ### Validation - At least one field required. - At least one category required. - Interval format validation: `[0-9]+[mhdw]` ### Returns - `StatsV2Response` - Statistics with time series data. - `string` - Full executed query URL. - `error` - Query error. ``` -------------------------------- ### Error Handling Pattern in Handlers Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/errors.md Demonstrates the common pattern for handling errors within Sentry datasource query handlers in Go. It includes validation for organization slug and error handling for API query execution. ```go func HandleIssues(client sentry.SentryClient, query query.SentryQuery, backendQuery backend.DataQuery, response backend.DataResponse) backend.DataResponse { // Validate org slug if client.OrgSlug == "" { return errors.GetErrorResponse(response, "", backend.DownstreamError( errors.ErrorInvalidOrganizationSlug)) } // Execute query data, queryStr, err := client.GetIssues(...) if err != nil { return errors.GetErrorResponse(response, queryStr, err) } // Process results... return response } ``` -------------------------------- ### Query Analysis Object Structure Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/PluginModule.md Illustrates the structure of the analyzed query data returned by the analyzeQueries function, showing counts for different Sentry query types. ```json { query_count: 5, issues_count: 2, events_count: 1, stats_count: 1, metrics_count: 1, // ... etc for each query type } ``` -------------------------------- ### List Projects for a Team Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/endpoints.md Retrieves a list of projects assigned to a specific team within an organization. Requires organization and team slugs. ```HTTP GET /api/0/teams/my-org/backend-team/projects Authorization: Bearer {authToken} ``` -------------------------------- ### Fetch Sentry Projects by Organization Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryDataSource.md Retrieves all projects within a specified Sentry organization. Use this to list projects for a given organization slug. ```typescript datasource.getProjects('my-org').then(projects => { projects.forEach(p => console.log(p.name, p.id)); }); ``` -------------------------------- ### GetEventsInput Struct Definition Source: https://github.com/grafana/sentry-datasource/blob/main/_autodocs/api-reference/SentryClientAPI.md Defines the input structure for fetching individual events from Sentry, allowing specification of fields, filters, and sorting. ```go type GetEventsInput struct { OrganizationSlug string ProjectIds []string Environments []string Fields []string Query string From time.Time To time.Time Sort string Limit int64 } ```