Skip to content

Migrated to web analytics build to TB Forward - #22859

Merged
9larsons merged 11 commits into
mainfrom
new-tb-directory
Apr 10, 2025
Merged

9larsons merged 11 commits into
mainfrom
new-tb-directory

Conversation

@9larsons

@9larsons 9larsons commented Apr 10, 2025 •

Copy link
Copy Markdown
Contributor

ref https://linear.app/ghost/issue/PROD-214

  • migrated all Tinybird assets to a new directory structure matching Tinybird Forward
  • migrated all tests to the new .yaml structure
  • updated scripts to handle Tinybird local + new directory
  • updated config handling to allow for TB Local config (+ some general improvements/cleaning up)

Tinybird Forward is the miles ahead of TB Classic when in comes to DevX and is going to be the future of their product. With that in mind, it'd be best to move over to it while we're building out the web analytics functionality. For the moment, we are running the two builds in parallel while we figure out deployments (CI/CD) with Tinybird Forward, as the VERSION field is fully deprecated.

The primary benefit is being able to develop locally with Tinybird Local, which runs in a Docker container. This commit adds the support to run alongside/within Ghost. See the readme file as part of this commit for instructions on how to configure Ghost's config.

@coderabbitai

coderabbitai Bot commented Apr 10, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

This update refactors several components in the Ghost admin stats and Tinybird integration modules. The changes primarily replace hardcoded API endpoint construction and token retrieval with dynamic calls to utility functions—getEndpointUrl and getToken—across multiple chart components (e.g., KPIs, technical, top-locations, top-pages, top-sources, and modal stats). In addition, utility functions in the stats module have been added or updated with detailed JSDoc comments, including new functions for generating a monochrome color palette and retrieving country flags. On the Tinybird side, new data source schemas, endpoints, and SQL pipelines have been introduced to support detailed analytics queries, along with corresponding readme and test files. Modifications in configuration and script commands in the package.json simplify the Tinybird local setup and installation process.

Possibly related PRs

  • Added Tinybird tests for remaining single filter test cases #22845: The changes in the main PR are related to those in the retrieved PR as both involve modifications to how API endpoints are constructed and tested, specifically focusing on the getEndpointUrl and getToken functions, which are utilized in the context of the top_sources endpoint.
  • Added Tinybird tests for the KPIs endpoint with compound filter #22846: The changes in the main PR regarding the updates to API endpoint and token retrieval methods in various components are related to the modifications in the retrieved PR, which focuses on testing the KPIs endpoint that utilizes similar API structures and filters.
  • Removed pageviews from traffic analytics pipe results #22839: The changes in the main PR are related to those in the retrieved PR as both involve modifications to how API endpoints and tokens are handled, specifically by removing hardcoded values and replacing them with utility functions, although the retrieved PR focuses on removing pageview metrics from SQL queries.

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between aa52426 and ea2ae33.

📒 Files selected for processing (1)
  • ghost/core/test/unit/frontend/public/ghost-stats.test.js (1 hunks)
🔇 Additional comments (1)
ghost/core/test/unit/frontend/public/ghost-stats.test.js (1)

47-51: Implementation aligns well with Tinybird Forward migration.

These changes correctly update the test configuration to support the migration to Tinybird Forward. The addition of the host and token properties ensures that tests properly exercise the updated Tinybird integration while maintaining the existing storage configuration.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (12)
ghost/core/core/frontend/public/ghost-stats.js (1)

147-147: URL construction looks good, but fix semicolon and indentation.

The change to use a dynamic host variable instead of a hardcoded URL is a good improvement for configuration flexibility, especially for supporting both cloud and local Tinybird environments.

Fix the semicolon and indentation issues:

-    const url = `${host}?name=${DATASOURCE}&token=${token}`
+        const url = `${host}?name=${DATASOURCE}&token=${token}`;
🧰 Tools
🪛 ESLint

[error] 146-147: Missing semicolon.

(semi)


[error] 147-147: Expected indentation of 8 spaces but found 4.

(indent)


[error] 147-148: Missing semicolon.

(semi)

ghost/core/core/server/data/tinybird/readme.md (1)

1-47: Comprehensive documentation for the Tinybird implementation.

The README provides clear instructions for setup, usage, and configuration of the Tinybird analytics integration. This will be valuable for developers working with this module.

Two minor improvements:

  1. Consider simplifying "In order to use" to "To use" in line 12 for conciseness
  2. Add a language specifier to the fenced code block at line 18:
-```
+```json
🧰 Tools
🪛 LanguageTool

[style] ~11-~11: Consider a shorter alternative to avoid wordiness.
Context: ...cker container running Tinybird local. In order to use tb local with Ghost, the config l...

(IN_ORDER_TO_PREMIUM)

🪛 markdownlint-cli2 (0.17.2)

18-18: Fenced code blocks should have a language specified
null

(MD040, fenced-code-language)

ghost/core/core/server/data/tinybird/endpoints/api_top_os.pipe (1)

48-49: Consider adding pagination information to the result.

The current implementation uses skip and limit for pagination but doesn't return the total count of available results, which might be useful for client-side pagination controls.

Consider adding a total count of available results, perhaps using a separate aggregate query or a WITH TOTALS modifier if supported by your database.

ghost/admin/app/components/stats/charts/top-sources.js (1)

92-98: Consider error handling for external favicon service.

While there is an onError handler for failed favicon loads, there might be rate limiting or other issues with the external favicon service that could affect user experience.

Consider implementing a fallback strategy for favicon loading, such as caching favicons or using a different service as backup.

- src={`https://www.faviconextractor.com/favicon/${label || 'direct'}?larger=true`}
+ src={this.getFaviconUrl(label || 'direct')}

With a helper method that could implement more robust fallback strategies:

getFaviconUrl(domain) {
  // Could implement caching, multiple services, or other fallback strategies
  return `https://www.faviconextractor.com/favicon/${domain}?larger=true`;
}
ghost/core/core/server/data/tinybird/pipes/filtered_sessions.pipe (2)

34-42: Additional filtering for source
Joining query_filters ensures that only sessions matching prior filters are considered. Watch for potential performance overhead if source usage is frequent—ensure an index or efficient join strategy.


5-27:

Details

❓ Verification inconclusive

Conditional filtering logic
Filters are applied only if parameters are defined, which is flexible.
Consider verifying that each of these filters aligns with available indexes (e.g., on site_uuid) to prevent full table scans on large data sets.


🏁 Script executed:

#!/bin/bash
# Check for indexes on `_mv_hits` for commonly used filters
# This is a mock query as an example, you may need to adapt to your actual DB environment
echo "SHOW CREATE TABLE _mv_hits;" 

Length of output: 64


Action Required: Verify Indexes on _mv_hits for Filtered Sessions Query

The conditional filtering logic looks flexible, but the executed query only printed the command (SHOW CREATE TABLE _mv_hits;) without providing actual index details. Please verify that the fields used in the filters—especially site_uuid and any date expressions based on timestamp—are supported by indexes. Without confirmed indexing, these filters could lead to full table scans on large datasets.

  • Double-check the available indexes on _mv_hits (e.g., for site_uuid and possibly on computed date values).
  • Ensure any computed filters (e.g., those using toDate(toTimezone(timestamp, ...))) are optimized to use indexes where applicable.
ghost/core/core/server/data/tinybird/pipes/mv_hits.pipe (2)

4-24: Initial data selection
Coalescing session_id and handling null referrer is sensible. Consider logging or tracking unusual user agents or null sessions if they appear frequently.


30-85: User agent classification logic
While relying on pattern matching covers many scenarios, it can miss corner cases. Consider a dedicated parser library to reduce maintenance overhead of manual regex updates.

ghost/core/core/server/data/tinybird/endpoints/api_kpis.pipe (2)

3-56: timeseries node
The date logic gracefully handles single-day vs. multi-day queries. Double-check large date range behavior to ensure no performance bottlenecks.


107-146: pathname_pageviews node
Integrates time-binning logic. The parameter checks for pathname are good; consider the same indexing approach if pathname queries are common.

ghost/core/core/server/data/tinybird/tests/api_kpis.yaml (2)

1-1: Nitpick: Remove extraneous leading blank lines.
Static analysis flagged an issue on line 1 due to too many blank lines. Removing them will improve overall file cleanliness.

🧰 Tools
🪛 YAMLlint (1.35.1)

[warning] 1-1: too many blank lines

(1 > 0) (empty-lines)


150-150: Nitpick: Remove Trailing Spaces.
Static analysis detected trailing spaces on line 150. Please remove these trailing spaces to improve formatting consistency.

🧰 Tools
🪛 YAMLlint (1.35.1)

[error] 150-150: trailing spaces

(trailing-spaces)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7fb0d56 and aa52426.

⛔ Files ignored due to path filters (1)
  • ghost/core/test/unit/frontend/helpers/__snapshots__/ghost_head.test.js.snap is excluded by !**/*.snap
📒 Files selected for processing (33)
  • ghost/admin/app/components/stats/charts/kpis.js (2 hunks)
  • ghost/admin/app/components/stats/charts/technical.js (2 hunks)
  • ghost/admin/app/components/stats/charts/top-locations.js (2 hunks)
  • ghost/admin/app/components/stats/charts/top-pages.js (2 hunks)
  • ghost/admin/app/components/stats/charts/top-sources.js (2 hunks)
  • ghost/admin/app/components/stats/kpis-overview.js (2 hunks)
  • ghost/admin/app/components/stats/modal-stats-all.js (2 hunks)
  • ghost/admin/app/utils/stats.js (4 hunks)
  • ghost/core/core/frontend/helpers/ghost_head.js (2 hunks)
  • ghost/core/core/frontend/public/ghost-stats.js (1 hunks)
  • ghost/core/core/server/data/tinybird/datasources/_mv_hits.datasource (1 hunks)
  • ghost/core/core/server/data/tinybird/datasources/analytics_events.datasource (1 hunks)
  • ghost/core/core/server/data/tinybird/endpoints/api_kpis.pipe (1 hunks)
  • ghost/core/core/server/data/tinybird/endpoints/api_top_browsers.pipe (1 hunks)
  • ghost/core/core/server/data/tinybird/endpoints/api_top_devices.pipe (1 hunks)
  • ghost/core/core/server/data/tinybird/endpoints/api_top_locations.pipe (1 hunks)
  • ghost/core/core/server/data/tinybird/endpoints/api_top_os.pipe (1 hunks)
  • ghost/core/core/server/data/tinybird/endpoints/api_top_pages.pipe (1 hunks)
  • ghost/core/core/server/data/tinybird/endpoints/api_top_sources.pipe (1 hunks)
  • ghost/core/core/server/data/tinybird/fixtures/analytics_events.ndjson (1 hunks)
  • ghost/core/core/server/data/tinybird/pipes/filtered_sessions.pipe (1 hunks)
  • ghost/core/core/server/data/tinybird/pipes/mv_hits.pipe (1 hunks)
  • ghost/core/core/server/data/tinybird/pipes/mv_session_data.pipe (1 hunks)
  • ghost/core/core/server/data/tinybird/readme.md (1 hunks)
  • ghost/core/core/server/data/tinybird/tests/api_kpis.yaml (1 hunks)
  • ghost/core/core/server/data/tinybird/tests/api_top_browsers.yaml (1 hunks)
  • ghost/core/core/server/data/tinybird/tests/api_top_devices.yaml (1 hunks)
  • ghost/core/core/server/data/tinybird/tests/api_top_locations.yaml (1 hunks)
  • ghost/core/core/server/data/tinybird/tests/api_top_os.yaml (1 hunks)
  • ghost/core/core/server/data/tinybird/tests/api_top_pages.yaml (1 hunks)
  • ghost/core/core/server/data/tinybird/tests/api_top_sources.yaml (1 hunks)
  • ghost/core/test/unit/frontend/helpers/ghost_head.test.js (3 hunks)
  • package.json (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (8)
ghost/core/core/frontend/public/ghost-stats.js (1)
ghost/core/core/frontend/helpers/ghost_head.js (1)
  • token (166-166)
ghost/admin/app/components/stats/charts/top-sources.js (1)
ghost/admin/app/utils/stats.js (2)
  • getEndpointUrl (272-276)
  • getToken (261-263)
ghost/admin/app/components/stats/modal-stats-all.js (1)
ghost/admin/app/utils/stats.js (2)
  • getEndpointUrl (272-276)
  • getToken (261-263)
ghost/core/test/unit/frontend/helpers/ghost_head.test.js (5)
ghost/core/test/unit/frontend/helpers/recommendations.test.js (1)
  • configUtils (6-6)
ghost/core/test/unit/frontend/helpers/get.test.js (1)
  • configUtils (5-5)
ghost/core/test/unit/server/data/db/backup.test.js (1)
  • configUtils (7-7)
ghost/core/test/unit/server/models/member.test.js (1)
  • configUtils (4-4)
ghost/core/test/unit/server/models/permission.test.js (1)
  • configUtils (4-4)
ghost/admin/app/components/stats/charts/top-pages.js (1)
ghost/admin/app/utils/stats.js (2)
  • getEndpointUrl (272-276)
  • getToken (261-263)
ghost/admin/app/components/stats/charts/kpis.js (1)
ghost/admin/app/utils/stats.js (2)
  • getEndpointUrl (272-276)
  • getToken (261-263)
ghost/admin/app/components/stats/kpis-overview.js (1)
ghost/admin/app/utils/stats.js (3)
  • getEndpointUrl (272-276)
  • params (214-219)
  • getToken (261-263)
ghost/admin/app/components/stats/charts/top-locations.js (1)
ghost/admin/app/utils/stats.js (2)
  • getEndpointUrl (272-276)
  • getToken (261-263)
🪛 ESLint
ghost/core/core/frontend/public/ghost-stats.js

[error] 146-147: Missing semicolon.

(semi)


[error] 147-147: Expected indentation of 8 spaces but found 4.

(indent)


[error] 147-148: Missing semicolon.

(semi)

🪛 LanguageTool
ghost/core/core/server/data/tinybird/readme.md

[style] ~11-~11: Consider a shorter alternative to avoid wordiness.
Context: ...cker container running Tinybird local. In order to use tb local with Ghost, the config l...

(IN_ORDER_TO_PREMIUM)

🪛 markdownlint-cli2 (0.17.2)
ghost/core/core/server/data/tinybird/readme.md

18-18: Fenced code blocks should have a language specified
null

(MD040, fenced-code-language)

🪛 Biome (1.9.4)
ghost/admin/app/utils/stats.js

[error] 156-157: This expression always returns false, because the string is converted and will never match

This call convert the string to upper case

... but this value is not in upper case

Unsafe fix: Use upper case string value.

(lint/correctness/noStringCaseMismatch)

🪛 YAMLlint (1.35.1)
ghost/core/core/server/data/tinybird/tests/api_kpis.yaml

[warning] 1-1: too many blank lines

(1 > 0) (empty-lines)


[error] 150-150: trailing spaces

(trailing-spaces)

⏰ Context from checks skipped due to timeout of 90000ms (13)
  • GitHub Check: Database tests (Node 20.11.1, sqlite3)
  • GitHub Check: Ghost-CLI tests
  • GitHub Check: Database tests (Node 22.13.1, mysql8)
  • GitHub Check: Database tests (Node 20.11.1, mysql8)
  • GitHub Check: Database tests (Node 18.12.1, mysql8)
  • GitHub Check: Signup-form tests
  • GitHub Check: Regression tests (Node 20.11.1, mysql8)
  • GitHub Check: Comments-UI tests
  • GitHub Check: Admin-X Settings tests
  • GitHub Check: Unit tests (Node 22.13.1)
  • GitHub Check: Unit tests (Node 20.11.1)
  • GitHub Check: Unit tests (Node 18.12.1)
  • GitHub Check: Admin tests - Chrome
🔇 Additional comments (65)
ghost/core/core/server/data/tinybird/endpoints/api_top_devices.pipe (1)

1-51: Well-structured new endpoint for device statistics.

This new endpoint implementation for retrieving device statistics is well-structured with appropriate filtering options. It properly handles various parameters for filtering by date range, member status, and device properties.

The SQL query is clearly formatted with conditional logic for all the optional filter parameters. The pagination implementation with skip and limit parameters also follows best practices.

ghost/core/core/server/data/tinybird/endpoints/api_top_sources.pipe (1)

1-24: Well-implemented top sources endpoint with clean SQL.

The implementation for retrieving top traffic sources is clean and follows good SQL practices. The conditional logic for date filtering is properly implemented.

I particularly like how the endpoint handles the special case when date_from and date_to are the same day (line 14), applying a more specific filter. The default date range fallback (last 7 days) is also a good user experience choice.

ghost/core/core/server/data/tinybird/tests/api_top_devices.yaml (1)

1-70: Well-structured test cases for the top devices API

The test suite provides comprehensive coverage of various filtering scenarios for device tracking statistics. The consistent structure with name, description, parameters, and expected results makes the tests clear and maintainable.

I particularly like how you've covered all important filtering combinations and included a test case with multiple filters (line 65-69), which is essential for validating more complex query scenarios.

ghost/core/core/server/data/tinybird/tests/api_top_pages.yaml (1)

1-87: Comprehensive test coverage for top pages API

The test cases are well-structured and provide thorough coverage for page visit statistics across multiple filtering scenarios. The consistent format makes the tests easy to understand and maintain.

The expected results for each test case clearly reflect what would be anticipated when applying different filters, and the inclusion of a test with multiple combined filters (lines 80-86) demonstrates the API's ability to handle complex query scenarios.

ghost/core/core/server/data/tinybird/fixtures/analytics_events.ndjson (1)

1-31: Well-designed test fixtures for analytics events

The analytics event fixtures provide a diverse dataset that covers various scenarios needed for comprehensive testing:

  • Multiple user types (paid, free, comped, undefined)
  • Various referral sources (search engines, direct visits)
  • Different countries and locales
  • Multiple device types and browsers
  • Various page visits and interaction patterns

This rich dataset will effectively support the testing of filtering, aggregation, and reporting features in the analytics API.

ghost/admin/app/components/stats/charts/top-locations.js (2)

9-9: Good refactoring to centralize utility imports

The updated import statement adds the necessary utility functions for handling endpoint URLs, tokens, and country flags. This aligns with the refactoring goals mentioned in the PR objectives.


65-67: Improved endpoint and token management

Replacing hardcoded endpoint construction with the getEndpointUrl and getToken utility functions improves maintainability by:

  1. Centralizing the logic for endpoint URL construction
  2. Supporting both local and remote Tinybird configurations
  3. Making the code more consistent across different components

This change aligns well with the PR objective of improving configuration handling and supporting Tinybird local configurations.

ghost/core/core/server/data/tinybird/endpoints/api_top_os.pipe (2)

1-52: Well-structured API endpoint with comprehensive filtering options.

The implementation of this new Tinybird pipe endpoint for operating system statistics is clean and follows best practices. The query handles all necessary filtering scenarios with appropriate defaults and type definitions for parameters.


14-23:

Details

❓ Verification inconclusive

Default date range differs from other endpoints.

I noticed that the default date range here uses -1 year whereas other similar endpoints (like api_top_pages.pipe) use -7 day. This inconsistency might lead to confusion when comparing data across different charts.

Was this difference in default date ranges intentional? Consider standardizing default date ranges across similar endpoints unless there's a specific requirement for different defaults.


🏁 Script executed:

#!/bin/bash
# Find all pipe files and check for different default date ranges
echo "Checking default date ranges in pipe files:"
fd -e pipe . ghost/core/core/server/data/tinybird/endpoints/ -x grep -A 3 "timestampAdd" {} \;

Length of output: 4268


Action Required: Verify and Standardize Default Date Ranges

It appears that the endpoint in ghost/core/core/server/data/tinybird/endpoints/api_top_os.pipe uses a default date range of one year (via timestampAdd(today(), interval -1 year)) when date_from is not provided, which contrasts with other endpoints (e.g., api_top_pages.pipe) that default to a 7-day range. This discrepancy might lead to confusion when comparing metrics across different charts.

  • Location: ghost/core/core/server/data/tinybird/endpoints/api_top_os.pipe (lines 14–23)
  • Issue: Inconsistent default date range settings—-1 year in this endpoint versus -7 day in others.
  • Recommendation: Confirm if the extended date range was an intentional design choice. If not, consider standardizing all similar endpoints to use a 7-day default. Alternatively, if the longer range is required, please add appropriate documentation to clarify the rationale.
ghost/admin/app/components/stats/charts/top-pages.js (2)

7-7: Great job refactoring to use utility functions.

The import changes properly introduce the utility functions for endpoint and token handling, improving code maintainability.


64-66: Well-implemented dynamic endpoint and token retrieval.

The changes properly utilize the utility functions getEndpointUrl and getToken to dynamically construct API endpoints and retrieve authentication tokens based on configuration. This approach supports the new Tinybird Forward directory structure and local configurations.

ghost/core/core/server/data/tinybird/endpoints/api_top_pages.pipe (3)

1-52: Properly structured API endpoint for top pages statistics.

The implementation of this new Tinybird pipe endpoint follows best practices with appropriate filtering, sorting, and pagination.


44-46: Clear documentation on source filtering approach.

Good use of comments to indicate that source filtering is handled in the filtered_sessions pipe rather than here. This prevents duplication of filtering logic and clarifies the implementation approach.


22-22: Default date range is set to 7 days.

The default date range of 7 days is appropriate for top pages statistics as it provides recent and relevant data for analysis.

ghost/admin/app/components/stats/charts/top-sources.js (2)

7-7: Consistent import changes across components.

The import changes align with the pattern used in other chart components, consistently adopting the utility functions for endpoint and token handling.


60-67: Robust implementation of API request parameters.

The changes properly use the utility functions for endpoint URL and token retrieval, while maintaining the existing getStatsParams function for query parameters. This approach ensures consistent handling of API requests across components.

ghost/core/core/server/data/tinybird/datasources/analytics_events.datasource (1)

1-14: Well-designed analytics event datasource configuration

This new datasource configuration for analytics events is well-structured with appropriate data types and storage engine settings. The use of LowCardinality for fields with limited distinct values and JSON with constraints for the payload will help with query performance. The partitioning by month and sorting by site_uuid and timestamp are excellent choices for typical analytics queries that filter by site and time ranges.

ghost/core/core/server/data/tinybird/endpoints/api_top_locations.pipe (1)

1-51: Comprehensive and well-structured API endpoint for location analytics

This API endpoint for retrieving top visitor locations is well-designed with:

  • Appropriate READ token permissions
  • Comprehensive parameter-based filtering with smart defaults
  • Proper handling of special cases (e.g., 'comped' members)
  • Efficient query structure using materialized views
  • Proper pagination support

The conditional logic handling various filter parameters is clear and maintainable, making this a robust implementation for location-based analytics.

ghost/admin/app/components/stats/charts/kpis.js (2)

9-9: Good refactoring of imports for better modularity

The updated import statement properly includes all required utility functions while removing the direct dependency on TB_VERSION, which aligns with the refactoring strategy.


26-28: Excellent refactoring for improved configuration handling

Replacing hardcoded endpoint construction and direct token access with the utility functions getEndpointUrl and getToken improves modularity and maintainability. This approach centralizes endpoint and token management logic, adding support for both regular and local development configurations.

ghost/admin/app/components/stats/modal-stats-all.js (3)

9-9: Good refactoring of imports for better modularity

The updated import statement properly includes all required utility functions including getCountryFlag, getEndpointUrl, and getToken, which aligns with the refactoring strategy.


84-97: Well-implemented endpoint URL construction refactoring

Replacing hardcoded endpoint URLs with the getEndpointUrl utility function across all three cases in the switch statement improves consistency and maintainability. This approach centralizes endpoint construction logic and supports both regular and local configurations.


104-104: Good refactoring of token retrieval

Replacing direct token access with the getToken utility function improves configuration handling by abstracting away the details of token retrieval and supporting both regular and local configurations.

ghost/admin/app/components/stats/kpis-overview.js (3)

6-6: Updated imports to use utility functions.

The import statement has been updated to include the utility functions getEndpointUrl and getToken from the stats utility module, which will handle endpoint URL construction and token retrieval more consistently.


65-67: Replaced hardcoded endpoint construction with utility functions.

The code now uses the getEndpointUrl and getToken functions to dynamically retrieve the endpoint URL and authorization token based on configuration. This improves code maintainability by centralizing the API endpoint and token retrieval logic.

These changes support the new Tinybird local configuration setup, allowing the component to automatically use the appropriate endpoint and token depending on whether local mode is enabled.


71-71: Updated Authorization header with dynamic token.

The Authorization header now uses the token retrieved from the getToken utility function, ensuring consistent token usage across the application.

ghost/core/core/server/data/tinybird/endpoints/api_top_browsers.pipe (3)

1-2: Added access token configuration for the top browsers endpoint.

The endpoint is configured with a READ token named "stats_page", which controls access permissions to this API.


3-51: Created new API endpoint for browser statistics.

This new endpoint provides browser usage analytics by:

  1. Querying the materialized view of hits (_mv_hits)
  2. Joining with filtered sessions
  3. Counting unique visits per browser
  4. Supporting various filtering parameters

The SQL implementation properly handles:

  • Site UUID filtering (required)
  • Date range filtering with defaults
  • Member status filtering with support for 'paid' and 'comped'
  • Optional filtering by device, browser, OS, source, location, and pathname
  • Pagination through skip and limit parameters

52-52: Marked the node as an endpoint type.

The TYPE ENDPOINT designation declares this pipe as a queryable API endpoint rather than an intermediate data transformation.

ghost/core/test/unit/frontend/helpers/ghost_head.test.js (5)

1456-1457: Updated the Tinybird tracker endpoint URL.

The endpoint has been changed from the previous hardcoded value to a new URL structure https://e.ghost.org/tb/web_analytics, aligning with the updated Tinybird Forward architecture mentioned in the PR objectives.


1459-1465: Added local configuration settings for Tinybird.

A new local configuration object has been added with properties for:

  • enabled: Flag to toggle local mode (default: false)
  • endpoint: Local endpoint URL for development
  • token: Token for local authentication
  • datasource: Data source name for local environment

This change supports local development and testing of Tinybird analytics, meeting the PR objective to improve configuration handling for local Tinybird setups.


1568-1568: Updated the data-datasource attribute test assertion.

The test assertion has been updated to match the new datasource value "analytics_events" instead of the previous "analytics_events_json_v1", ensuring tests pass with the updated configuration.


1581-1591: Added test to verify correct endpoint URL from configuration.

This new test ensures that the correct host/endpoint from the configuration is properly included in the rendered HTML output, validating that the endpoint URLs are correctly applied.


1593-1605: Added test for local tracker script inclusion.

This test verifies that when the local Tinybird configuration is enabled, the tracker correctly uses the local endpoint URL. This ensures the local development setup works as expected, supporting the PR objective to accommodate Tinybird local configurations.

ghost/core/core/server/data/tinybird/datasources/_mv_hits.datasource (2)

3-20: Defined schema for the hits materialized view.

This schema defines the structure for the _mv_hits materialized view with appropriate data types for each field:

  • Uses LowCardinality(String) for fields with limited unique values (site_uuid, action, version) to optimize storage and query performance
  • Includes fields for tracking user sessions, member data, post information, and client details
  • Provides comprehensive analytics capabilities through browser, OS, and device tracking

This schema supports the analytics queries in endpoints like the new api_top_browsers.pipe.


21-23: Configured MergeTree engine with optimized partitioning and sorting.

The schema uses:

  1. MergeTree engine for efficient storage and querying of time-series data
  2. Monthly partitioning based on timestamp for optimized data management
  3. Sorting by site_uuid, timestamp, and session_id to accelerate common query patterns

This configuration balances query performance with storage efficiency for analytics data.

ghost/admin/app/components/stats/charts/technical.js (5)

6-6: Import cleanup is correct and centralizes utility usage
The new imports streamline token and endpoint handling.


50-50: Switched to dynamic endpoint for browsers
Good move to eliminate hardcoded references and rely on getEndpointUrl.


55-55: Switched to dynamic endpoint for OS
Maintaining consistency with getEndpointUrl ensures cohesive endpoint resolution.


60-60: Switched to dynamic endpoint for devices
Again, a straightforward update maintaining the new pattern for dynamic endpoints.


67-67: Token retrieval via getToken
Encapsulating token retrieval improves maintainability and clarity.

ghost/core/core/server/data/tinybird/pipes/filtered_sessions.pipe (2)

1-4: Node name matches functionality
Defining query_filters clearly conveys the purpose of extracting session criteria.


29-33: Second node clarity
sessions_filtered_by_source seamlessly extends the filters for source-based constraints.

ghost/core/core/server/data/tinybird/pipes/mv_hits.pipe (3)

1-3: Node definition for mv_hits_0
Straightforward creation of the node; the naming is descriptive.


27-29: Node definition for mv_hits_1
Clear separation of transformations into multiple nodes enhances readability.


86-88:

Details

❓ Verification inconclusive

Materialized output
Defining _mv_hits as materialized cements the pipeline’s final destination. Verify that the schema of _mv_hits matches the projected columns.


🏁 Script executed:

#!/bin/bash
# Compare columns in mv_hits.pipe with the schema definition
# to confirm they match the final datasource `_mv_hits`.
rg "CREATE TABLE _mv_hits" -A 20

Length of output: 34


Schema Verification Needed for _mv_hits

It appears that running the initial verification script did not yield any schema details (e.g., a CREATE TABLE _mv_hits statement) to compare with the projected columns in the pipe. Since the file currently only contains:

TYPE materialized
DATASOURCE _mv_hits

there’s no automated evidence that the table schema is being defined or validated in this file. Please manually verify that the projected columns coming through this pipeline match the intended schema for _mv_hits.

ghost/core/core/server/data/tinybird/endpoints/api_kpis.pipe (4)

58-88: session_metrics node
Joining filtered_sessions with mv_session_data for bounce rate, session duration, etc. looks correct. Confirm that merged data is tested for boundary conditions (e.g., extremely short or long sessions).


89-106: data node for aggregating KPIs
Comprehensive grouping by date or hour. The use of uniq(distinct s.session_id) is suitable for visit counts.


147-161: Final endpoint composition
Merging metrics in finished_data with left joins ensures no data is lost. coalesce usage for missing fields is a neat approach to fill in zeros.


1-2:

Details

✅ Verification successful

Token definition
Allowing read access for stats_page is clear; confirm that scoping is correct for the intended usage.


🏁 Script executed:

#!/bin/bash
# Check the usage of the 'stats_page' token in code references
rg "stats_page" -A 5

Length of output: 6057


Token "stats_page" Usage Verified — No Changes Required

The linting script and our grep search confirm that TOKEN "stats_page" READ is consistently declared in all related endpoints, including in ghost/core/core/server/data/tinybird/endpoints/api_kpis.pipe. The scoping aligns with the intended read-only access, and there are no discrepancies in its usage.

ghost/core/core/server/data/tinybird/tests/api_top_locations.yaml (1)

1-96: Well-structured test suite for the top locations API!

This comprehensive test suite covers all essential filtering scenarios for the top locations API. The test cases systematically verify API behavior with different filter combinations (browser, device, location, OS, pathname, source) and include important edge cases like member status filtering and timezone handling.

The test data uses future dates (2100-01-01), which is a good practice to ensure tests don't unintentionally match real production data.

ghost/core/core/server/data/tinybird/pipes/mv_session_data.pipe (2)

1-13: Well-designed session data aggregation node!

The mv_hits_0 node effectively aggregates session-level metrics from the _mv_hits table. The SQL query appropriately:

  • Groups by site_uuid and session_id to correctly define session boundaries
  • Uses Tinybird's aggregation functions to calculate pageviews and session timestamps
  • Captures the original traffic source with argMin(source, timestamp)

Note that for sessions with multiple sources, only the first source (earliest timestamp) will be captured due to the argMin function, which is typically the desired behavior for attribution.


16-28: Clean implementation of session metrics calculation!

The data node effectively processes the aggregated data to calculate key session metrics:

  • Session duration calculation is implemented correctly
  • Bounce detection uses the standard definition (single pageview sessions)
  • All fields are properly selected and preserved from the upstream node

This implementation follows analytics best practices for session-based metrics.

ghost/core/core/server/data/tinybird/tests/api_top_browsers.yaml (1)

1-90: Comprehensive test suite for the top browsers API!

This well-structured test suite thoroughly covers the top browsers API functionality with a systematic approach:

  • Base case testing with just date range filtering
  • Individual filter testing (browser, device, location, OS, pathname, source)
  • Member status filtering tests for both paid and undefined statuses
  • Timezone handling verification
  • Multi-filter combination testing

The test cases provide good coverage for verifying the API's filtering capabilities and expected response format.

ghost/core/core/server/data/tinybird/tests/api_top_os.yaml (1)

1-74: Well-designed test suite for the top operating systems API!

This test suite follows the same systematic approach as the other API test files, providing consistent validation across all dimensions:

  • Base case with just date filtering
  • Individual filter validation
  • Member status filtering
  • Timezone handling
  • Combined filter testing

The consistency in test structure across all the API test files makes the codebase more maintainable and easier to understand.

ghost/core/core/frontend/helpers/ghost_head.js (2)

159-168: Improved Tinybird configuration handling with local support.

The code now adds proper support for local Tinybird configuration, allowing developers to switch between production and local environments. This enhances the development workflow and testing capabilities.


367-367: Simplified condition for Tinybird tracker inclusion.

The condition for including the Tinybird tracker has been simplified to just check for the existence of tinybird and tinybird:tracker config values, removing the unnecessary check for tinybird:tracker:scriptUrl.

package.json (2)

60-60: Simplified Tinybird local startup command.

The complex Docker command has been replaced with a simple tb local start command, which greatly improves developer experience and makes the local setup process more straightforward.


62-63: Added new Tinybird Forward commands for installation and development.

These new commands facilitate the installation and development workflow for Tinybird Forward, making it easier for developers to get started with the platform.

ghost/admin/app/utils/stats.js (4)

55-61: Enhanced documentation with JSDoc comments.

Adding comprehensive JSDoc comments to functions improves code readability and provides better context for developers working with these utilities.

Also applies to: 68-73, 150-154, 163-167, 175-179, 203-209


74-142: Added new utility function for generating monochrome color palettes.

The new generateMonochromePalette function provides a powerful tool for creating consistent color schemes based on a single base color. The implementation is thorough, handling both dark and light base colors appropriately.


256-263: Added utility function for retrieving the appropriate token.

The new getToken function encapsulates the logic for determining which token to use based on configuration, improving code organization and reusability.


265-276: Added utility function for building endpoint URLs.

The getEndpointUrl function standardizes the construction of API endpoint URLs, handling the differences between local and production environments and including versioning. This improves maintainability by centralizing this logic.

ghost/core/core/server/data/tinybird/tests/api_top_sources.yaml (1)

1-119: Well-structured comprehensive test cases for top sources API.

This new test file provides thorough coverage for the top sources API, with test cases for various filter combinations including browser, device, location, OS, pathname, source, member status, and timezone. The expected results are clearly defined for each scenario.

A few observations:

  1. All test dates are set in the future (2100-01-01), ensuring tests won't become outdated
  2. The tests include both single filter and multiple filter scenarios
  3. Expected results are well-formatted and consistent

This is a good approach to ensure API functionality remains stable through future changes.

ghost/core/core/server/data/tinybird/tests/api_kpis.yaml (1)

2-149: Approval: Comprehensive and Consistent Test Suite.
The new YAML file clearly defines a broad set of test cases for API KPIs, covering various filtering parameters (e.g., date ranges, browser, device, location, OS, pathname, source, member status, and timezone). The parameters and expected JSON results are uniformly formatted, which enhances readability and ensures thorough testing of the analytics functionality. Make sure that the corresponding endpoints and utility functions (e.g., those for Tinybird analytics integration) are in sync with these tests.

Also applies to: 151-208

Comment on lines +155 to +161
export function getCountryFlag(countryCode) {
if (!countryCode || countryCode === null || countryCode.toUpperCase() === 'ᴺᵁᴸᴸ') {
return '🏳️';
}
return countryCode.toUpperCase().replace(/./g, char => String.fromCodePoint(char.charCodeAt(0) + 127397)
);
};
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix potential string comparison issue in getCountryFlag.

There's a potential issue with the string case comparison in this function.

 if (!countryCode || countryCode === null || countryCode.toUpperCase() === 'ᴺᵁᴸᴸ') {
-    return '🏳️';
+    return '🏳️';
 }

According to static analysis, the comparison countryCode.toUpperCase() === 'ᴺᵁᴸᴸ' will always be false because 'ᴺᵁᴸᴸ' is not in uppercase. Consider replacing with:

-if (!countryCode || countryCode === null || countryCode.toUpperCase() === 'ᴺᵁᴸᴸ') {
+if (!countryCode || countryCode === null || countryCode.toUpperCase() === 'NULL') {
     return '🏳️';
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export function getCountryFlag(countryCode) {
if (!countryCode || countryCode === null || countryCode.toUpperCase() === 'ᴺᵁᴸᴸ') {
return '🏳️';
}
return countryCode.toUpperCase().replace(/./g, char => String.fromCodePoint(char.charCodeAt(0) + 127397)
);
};
}
export function getCountryFlag(countryCode) {
if (!countryCode || countryCode === null || countryCode.toUpperCase() === 'NULL') {
return '🏳️';
}
return countryCode.toUpperCase().replace(/./g, char => String.fromCodePoint(char.charCodeAt(0) + 127397)
);
}
🧰 Tools
🪛 Biome (1.9.4)

[error] 156-157: This expression always returns false, because the string is converted and will never match

This call convert the string to upper case

... but this value is not in upper case

Unsafe fix: Use upper case string value.

(lint/correctness/noStringCaseMismatch)

@9larsons
9larsons enabled auto-merge (squash) April 10, 2025 16:34
@9larsons
9larsons merged commit 70cf6ad into main Apr 10, 2025
@9larsons
9larsons deleted the new-tb-directory branch April 10, 2025 16:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant