Repository navigation
Migrated to web analytics build to TB Forward - #22859
Conversation
WalkthroughThis 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— Possibly related PRs
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
🔇 Additional comments (1)
✨ Finishing Touches
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
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
hostvariable 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:
- Consider simplifying "In order to use" to "To use" in line 12 for conciseness
- 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 usetb localwith 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 TOTALSmodifier 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
Joiningquery_filtersensures that only sessions matching prior filters are considered. Watch for potential performance overhead ifsourceusage 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., onsite_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_hitsfor Filtered Sessions QueryThe 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—especiallysite_uuidand any date expressions based ontimestamp—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., forsite_uuidand 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
Coalescingsession_idand handling nullreferreris 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:timeseriesnode
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_pageviewsnode
Integrates time-binning logic. The parameter checks forpathnameare good; consider the same indexing approach ifpathnamequeries 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
⛔ Files ignored due to path filters (1)
ghost/core/test/unit/frontend/helpers/__snapshots__/ghost_head.test.js.snapis 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
skipandlimitparameters 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_fromanddate_toare 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 APIThe 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 APIThe 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 eventsThe 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 importsThe 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 managementReplacing hardcoded endpoint construction with the
getEndpointUrlandgetTokenutility functions improves maintainability by:
- Centralizing the logic for endpoint URL construction
- Supporting both local and remote Tinybird configurations
- 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 yearwhereas 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.pipeuses a default date range of one year (viatimestampAdd(today(), interval -1 year)) whendate_fromis 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 yearin this endpoint versus-7 dayin 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
getEndpointUrlandgetTokento 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 configurationThis 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 analyticsThis 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 modularityThe 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 handlingReplacing hardcoded endpoint construction and direct token access with the utility functions
getEndpointUrlandgetTokenimproves 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 modularityThe updated import statement properly includes all required utility functions including
getCountryFlag,getEndpointUrl, andgetToken, which aligns with the refactoring strategy.
84-97: Well-implemented endpoint URL construction refactoringReplacing hardcoded endpoint URLs with the
getEndpointUrlutility 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 retrievalReplacing direct token access with the
getTokenutility 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
getEndpointUrlandgetTokenfrom 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
getEndpointUrlandgetTokenfunctions 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
getTokenutility 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:
- Querying the materialized view of hits (
_mv_hits)- Joining with filtered sessions
- Counting unique visits per browser
- 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 ENDPOINTdesignation 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
localconfiguration object has been added with properties for:
enabled: Flag to toggle local mode (default: false)endpoint: Local endpoint URL for developmenttoken: Token for local authenticationdatasource: Data source name for local environmentThis 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_hitsmaterialized 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:
- MergeTree engine for efficient storage and querying of time-series data
- Monthly partitioning based on timestamp for optimized data management
- 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 ongetEndpointUrl.
55-55: Switched to dynamic endpoint for OS
Maintaining consistency withgetEndpointUrlensures 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 viagetToken
Encapsulating token retrieval improves maintainability and clarity.ghost/core/core/server/data/tinybird/pipes/filtered_sessions.pipe (2)
1-4: Node name matches functionality
Definingquery_filtersclearly conveys the purpose of extracting session criteria.
29-33: Second node clarity
sessions_filtered_by_sourceseamlessly extends the filters for source-based constraints.ghost/core/core/server/data/tinybird/pipes/mv_hits.pipe (3)
1-3: Node definition formv_hits_0
Straightforward creation of the node; the naming is descriptive.
27-29: Node definition formv_hits_1
Clear separation of transformations into multiple nodes enhances readability.
86-88:Details
❓ Verification inconclusive
Materialized output
Defining_mv_hitsas materialized cements the pipeline’s final destination. Verify that the schema of_mv_hitsmatches 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 20Length 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_hitsstatement) to compare with the projected columns in the pipe. Since the file currently only contains:TYPE materialized DATASOURCE _mv_hitsthere’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_metricsnode
Joiningfiltered_sessionswithmv_session_datafor 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:datanode for aggregating KPIs
Comprehensive grouping by date or hour. The use ofuniq(distinct s.session_id)is suitable for visit counts.
147-161: Final endpoint composition
Merging metrics infinished_datawith left joins ensures no data is lost.coalesceusage for missing fields is a neat approach to fill in zeros.
1-2:Details
✅ Verification successful
Token definition
Allowing read access forstats_pageis 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 5Length of output: 6057
Token "stats_page" Usage Verified — No Changes Required
The linting script and our grep search confirm that
TOKEN "stats_page" READis consistently declared in all related endpoints, including inghost/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_0node effectively aggregates session-level metrics from the_mv_hitstable. The SQL query appropriately:
- Groups by
site_uuidandsession_idto 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
argMinfunction, which is typically the desired behavior for attribution.
16-28: Clean implementation of session metrics calculation!The
datanode 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
tinybirdandtinybird:trackerconfig values, removing the unnecessary check fortinybird:tracker:scriptUrl.package.json (2)
60-60: Simplified Tinybird local startup command.The complex Docker command has been replaced with a simple
tb local startcommand, 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
generateMonochromePalettefunction 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
getTokenfunction 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
getEndpointUrlfunction 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:
- All test dates are set in the future (2100-01-01), ensuring tests won't become outdated
- The tests include both single filter and multiple filter scenarios
- 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
| export function getCountryFlag(countryCode) { | ||
| if (!countryCode || countryCode === null || countryCode.toUpperCase() === 'ᴺᵁᴸᴸ') { | ||
| return '🏳️'; | ||
| } | ||
| return countryCode.toUpperCase().replace(/./g, char => String.fromCodePoint(char.charCodeAt(0) + 127397) | ||
| ); | ||
| }; | ||
| } |
There was a problem hiding this comment.
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.
| 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)
ref https://linear.app/ghost/issue/PROD-214
.yamlstructureTinybird 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
VERSIONfield 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.