Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions deploy/site.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ def deploy(m, root, metadata, receipt):
d.require(aws.call('s3api', 'get-bucket-versioning', Bucket=m['bucket']).get('Status') == 'Enabled', 'Enable bucket versioning before release')
release = sha + '-' + os.environ.get('CIRCLE_BUILD_NUM', '')
d.require(re.fullmatch(r'[a-f0-9]{40}-[0-9]{1,12}', release), 'Invalid release identity')
entries = {'asset-manifest.json': root / 'asset-manifest.json', 'index.html': root / 'index.html', 'gigs/index.html': root / 'index.html', 'timeline-wall/index.html': root / 'index.html'}
entries = {'asset-manifest.json': root / 'asset-manifest.json', 'index.html': root / 'index.html', 'gigs/index.html': root / 'index.html', 'timeline-wall/index.html': root / 'index.html', 'statistics/index.html': root / 'index.html'}
with tempfile.TemporaryDirectory(prefix='platform-ui-rollback-') as directory:
previous = {}
for number, key in enumerate(entries):
Expand All @@ -262,13 +262,13 @@ def deploy(m, root, metadata, receipt):
info = aws.call('s3api', 'get-object', extra=(str(target),), Bucket=m['bucket'], Key=key)
previous[key] = (target, info.get('VersionId'))
except d.DeployError as exc:
if key not in ('gigs/index.html', 'timeline-wall/index.html') or not re.search(r'\((NoSuchKey|404)\)|: (NoSuchKey|404)$', str(exc)):
if key not in ('gigs/index.html', 'timeline-wall/index.html', 'statistics/index.html') or not re.search(r'\((NoSuchKey|404)\)|: (NoSuchKey|404)$', str(exc)):
raise
previous[key] = previous['index.html']
promoted = False
try:
aws.sync(root, m['bucket'], ['--exclude', '*', '--include', 'static/*'], 'public,max-age=31536000,immutable')
aws.sync(root, m['bucket'], ['--exclude', 'static/*', '--exclude', 'index.html', '--exclude', 'gigs/index.html', '--exclude', 'timeline-wall/index.html', '--exclude', 'asset-manifest.json'], NO_CACHE)
aws.sync(root, m['bucket'], ['--exclude', 'static/*', '--exclude', 'index.html', '--exclude', 'gigs/index.html', '--exclude', 'timeline-wall/index.html', '--exclude', 'statistics/index.html', '--exclude', 'asset-manifest.json'], NO_CACHE)
for key, path in entries.items():
promoted = True
put(aws, m, key, path, sha)
Expand Down
8 changes: 4 additions & 4 deletions deploy/tests/test_site.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,10 +146,10 @@ def test_failed_public_verification_restores_previous_shells(self):
with patch.object(site, 'check_job', return_value='a' * 40), patch.object(site, 'verify_artifact'), patch.object(site, 'authenticate', return_value=aws), patch.object(site, 'invalidate', return_value='invalidation'), patch.object(site, 'urlopen', side_effect=OSError('network')), patch.dict(os.environ, {'CIRCLE_BUILD_NUM': '1'}):
with self.assertRaises(OSError):
site.deploy(self.m, root, self.root / 'artifact.json', self.root / 'receipt.json')
self.assertEqual(len(aws.puts), 8)
self.assertTrue(all(body == b'previous' for _, body in aws.puts[-4:]))
self.assertEqual([key for key, _ in aws.puts[-4:]],
['asset-manifest.json', 'index.html', 'gigs/index.html', 'timeline-wall/index.html'])
self.assertEqual(len(aws.puts), 10)
self.assertTrue(all(body == b'previous' for _, body in aws.puts[-5:]))
self.assertEqual([key for key, _ in aws.puts[-5:]],
['asset-manifest.json', 'index.html', 'gigs/index.html', 'timeline-wall/index.html', 'statistics/index.html'])


class FakeAWS:
Expand Down
65 changes: 65 additions & 0 deletions infrastructure/statistics-routing/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# Public statistics migration

`src/apps/statistics` restores the public community statistics page in Platform UI.
The General, Development, Design, QA, SRM, and Marathon Match categories use the
existing public `/v6/reports/statistics` endpoints. Totals, sortable/filterable
reports, member profile links, pagination, empty states, and retry are available
without signing in. SRM/MM reports are historical snapshots, as in the API.

## Routes and release

- `statistics.topcoder-dev.com` / `statistics.topcoder.com`: Platform UI distribution
aliases, covered by the existing wildcard ACM certificates. Public Route 53 A
aliases target the respective platform distribution; add AAAA only when IPv6 is enabled.
- `topcoder-dev.com/statistics` / `topcoder.com/statistics` (including `www` and
category paths): website viewer function selects the existing private Platform UI
origin and requests `/statistics/index.html`. Apex canonicalizes to `www`.
- `/community/statistics` and descendants: permanent redirects to `/statistics`,
retaining category suffixes and encoded/repeated query parameters. Platform UI
also supplies a client redirect for SPA navigation, retaining the fragment.
- Insert `platform-host-fragment.js` after the host lookup in the **current** platform
viewer function. Preserve all existing Contact, Accounts, TopGear, and Timeline logic.
- Add the new statistics origin to the existing Universal Navigation CORS policy.
The reports API already permits public browser requests.
- Grant the website distribution `s3:GetObject` on only `statistics/index.html`
in the existing platform bucket, retaining all other policy statements.

The website source change belongs to `topcoder-website/infra/aws/site.yml`.
Apply its narrow function change to the current deployed CloudFormation template,
retaining independently installed Timeline/Gigs behaviors and all unrelated resources.
Review a change set before execution. Never replace a live template with a stale checkout.

Build each environment with its pinned browser configuration. Upload immutable
`static/` assets first and publish only `statistics/index.html` for an isolated
pre-merge release; preserve shared root HTML and existing assets. After merge,
`deploy/site.py` promotes and rolls back the statistics shell alongside the other
entry points. Existing website `/static/` routing serves the assets from Platform UI.

Before activation, capture templates/parameters, functions/configuration/ETags,
bucket policies, navigation CORS policy, distribution aliases, and DNS. Re-read
before each write and preserve concurrent changes. Wait for CloudFormation
`UPDATE_COMPLETE`, CloudFront `Deployed`, DNS `INSYNC`, and completed invalidations.
Verify all host/path variants, deep links, queries, categories, API responses,
mobile layout, and unrelated website/platform smoke checks.

## Rollback

Restore the prior statistics HTML object version, remove only the added host aliases
and DNS records, and revert the marked statistics function code and website function
change with current ETags. Remove only the statistics bucket grant and navigation
CORS origin. Preserve assets for open tabs. Invalidate the statistics and legacy paths.

## Validation

```sh
yarn tsc --noEmit
yarn eslint src/apps/statistics src/config/constants.ts src/apps/platform/src/platform.routes.tsx
yarn craco test --watchAll=false --runInBand src/apps/statistics
python3 -m unittest discover -s infrastructure/statistics-routing
python3 -m unittest discover -s deploy/tests
```

The website viewer tests cover both environments and retirement modes. The related
reports-api change prevents service-account member IDs from breaking first-time
submitter reports; its PostgreSQL regression checks preserve earliest-submission
and maximum-rating semantics.
10 changes: 10 additions & 0 deletions infrastructure/statistics-routing/platform-host-fragment.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Public statistics shell; keep shared assets and all other hosts unchanged.
if (host === 'statistics.topcoder-dev.com' || host === 'statistics.topcoder.com'
|| host === 'statistics.topcoder-dev.com:443' || host === 'statistics.topcoder.com:443') {
if (request.uri.indexOf('/static/') === 0
|| ['/global.css', '/favicon.png', '/manifest.json', '/logo_512x512.png', '/robots.txt'].indexOf(request.uri) !== -1) {
return request;
}
request.uri = '/statistics/index.html';
return request;
}
29 changes: 29 additions & 0 deletions infrastructure/statistics-routing/test_routes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
"""Execute the hostname fragment and check the surrounding platform routes are unchanged."""
from pathlib import Path
import subprocess
import unittest


class HostRoutingTest(unittest.TestCase):
def test_host_shell_and_asset_isolation(self):
fragment = Path(__file__).with_name('platform-host-fragment.js').read_text()
source = 'function handler(event) { var request = event.request; var host = request.headers.host.value;\n'
source += fragment + '\nreturn request; }\n'
checks = r'''
const assert = require('node:assert/strict');
function run(host, uri) { return handler({ request: { headers: {host: {value: host}}, uri } }).uri; }
for (const env of ['topcoder-dev.com', 'topcoder.com']) {
for (const port of ['', ':443']) {
for (const uri of ['/', '/design', '/statistics', '/statistics/qa']) {
assert.equal(run('statistics.' + env + port, uri), '/statistics/index.html');
}
for (const uri of ['/static/js/main.js', '/global.css', '/manifest.json']) {
assert.equal(run('statistics.' + env + port, uri), uri);
}
}
for (const host of ['platform-ui.', 'sales.', 'timeline.', 'topgear.', 'account-settings.']) {
for (const uri of ['/', '/design', '/challenges']) assert.equal(run(host + env, uri), uri);
}
}
'''
subprocess.run(['node', '-e', source + checks], check=True)
2 changes: 2 additions & 0 deletions src/apps/platform/src/platform.routes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { forumsRoutes } from '~/apps/forums'
import { legacyOpportunityRoutes, opportunitiesRoutes, topgearRoutes } from '~/apps/opportunities'
import { analyticsRoutes } from '~/apps/analytics'
import { contactRoutes } from '~/apps/contact'
import { statisticsRoutes } from '~/apps/statistics'
import { gigsRoutes } from '~/apps/gigs'

const Home: LazyLoadedComponent = lazyLoad(
Expand Down Expand Up @@ -68,6 +69,7 @@ export const platformRoutes: Array<PlatformRoute> = [
...forumsRoutes,
...timelineWallRoutes,
...gigsRoutes,
...statisticsRoutes,
...devCenterRoutes,
...campusRoutes,
...copilotsRoutes,
Expand Down
1 change: 1 addition & 0 deletions src/apps/statistics/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { statisticsRoutes } from './src/statistics.routes'
125 changes: 125 additions & 0 deletions src/apps/statistics/src/ReportTable.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import { ChangeEvent, FC, MouseEvent, useState } from 'react'
import useSWR from 'swr'

import { EnvironmentConfig } from '~/config'

import { Column, Report, ReportRow } from './reports'
import { fetchStatistics, formatValue, reportOptions } from './statistics.service'
import styles from './StatisticsPage.module.scss'

interface Props { report: Report }
interface Sort { field: string; ascending: boolean }

/** Sortable public report with bounded rendering, filtering, and retryable errors. */
const ReportTable: FC<Props> = (props: Props) => {
const report = props.report
const result = useSWR(report.path, fetchStatistics, reportOptions)
const [sort, setSort] = useState<Sort>()
const [search, setSearch] = useState('')
const [limit, setLimit] = useState(25)
const rows = (result.data || []).filter(row => report.columns.some(column => (
String(row[column.field] ?? '')
.toLowerCase()
.includes(search.toLowerCase())
)))
if (sort) {
rows.sort((a: ReportRow, b: ReportRow) => {
const comparison = String(a[sort.field] ?? '')
.localeCompare(String(b[sort.field] ?? ''), 'en', { numeric: true })
return sort.ascending ? comparison : -comparison
})
}

function retry(): void { result.mutate() }
function showMore(): void { setLimit(limit + 25) }
function filter(event: ChangeEvent<HTMLInputElement>): void {
setSearch(event.target.value)
setLimit(25)
}

function sortColumn(event: MouseEvent<HTMLButtonElement>): void {
const field = event.currentTarget.dataset.field || ''
setSort({ ascending: sort?.field === field ? !sort.ascending : false, field })
}

function sortDirection(column: Column): 'ascending' | 'descending' | 'none' {
return sort?.field === column.field ? (sort.ascending ? 'ascending' : 'descending') : 'none'
}

const headingId = report.path.replace(/\//g, '-')
return (
<section className={styles.report} aria-labelledby={headingId}>
<h2 id={headingId}>{report.title}</h2>
{result.error && (
<div role='alert'>
Statistics could not be loaded.
{' '}
<button type='button' onClick={retry}>Retry</button>
</div>
)}
{!result.data && !result.error && <p role='status'>Loading statistics…</p>}
{result.data && !result.error && (
<>
<label className={styles.search}>
<span>{`Filter ${report.title.toLowerCase()}`}</span>
<input value={search} onChange={filter} type='search' />
</label>
{!rows.length ? (
<p role='status'>
{result.data.length ? 'No matching results.' : 'No statistics available yet.'}
</p>
) : (
<>
<div className={styles.tableScroll}>
<table>
<thead>
<tr>
<th scope='col'>Rank</th>
{report.columns.map(column => (
<th key={column.field} scope='col' aria-sort={sortDirection(column)}>
<button
type='button'
data-field={column.field}
onClick={sortColumn}
>
{column.label}
<span aria-hidden> ↕</span>
</button>
</th>
))}
</tr>
</thead>
<tbody>
{rows.slice(0, limit)
.map(row => (
<tr key={(result.data || []).indexOf(row)}>
<td>{row.rank ?? ((result.data || []).indexOf(row) + 1)}</td>
{report.columns.map(column => (
<td key={column.field}>
{column.member && row[column.field] ? (
<a href={`${EnvironmentConfig.USER_PROFILE_URL}/${
encodeURIComponent(String(row[column.field]))}`}
>
{formatValue(row[column.field], true)}
</a>
) : formatValue(row[column.field])}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
<div className={styles.pagination}>
<span>{`${Math.min(limit, rows.length)} of ${rows.length} results`}</span>
{limit < rows.length && <button type='button' onClick={showMore}>Show more</button>}
</div>
</>
)}
</>
)}
</section>
)
}

export default ReportTable
14 changes: 14 additions & 0 deletions src/apps/statistics/src/StatisticsPage.module.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
.page { max-width: 1440px; margin: 0 auto; padding: 40px 32px 64px; color: #1e293b; }
.header { margin-bottom: 32px; h1 { font-size: 48px; margin: 8px 0 16px; } p { line-height: 1.6; } p:first-child { font-size: 12px; font-weight: 700; letter-spacing: 2px; } }
.totals { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; margin-bottom: 32px; }
.total { padding: 24px; background: #e9f7f1; border-radius: 12px; display: flex; flex-direction: column; gap: 12px; strong { font-size: 32px; } }
.nav { display: flex; gap: 8px; flex-wrap: wrap; border-bottom: 1px solid #ccd6db; margin-bottom: 28px; a { padding: 14px 20px; color: #334155; text-decoration: none; border-bottom: 3px solid transparent; } a[aria-current] { color: #0a6747; border-color: #0a6747; font-weight: 700; } }
.reports { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 24px; align-items: start; }
.report { padding: 24px; border: 1px solid #d9e1e7; border-radius: 12px; background: white; h2 { font-size: 22px; margin: 0 0 20px; } button { cursor: pointer; } a { color: #086e53; text-decoration: underline; } }
.search { display: flex; flex-direction: column; gap: 8px; font-size: 13px; margin-bottom: 20px; input { padding: 10px 12px; border: 1px solid #8a98a6; border-radius: 6px; width: 100%; } }
.tableScroll { overflow: auto; max-height: 600px; table { width: 100%; border-collapse: collapse; font-size: 14px; } th, td { text-align: left; padding: 12px 10px; border-bottom: 1px solid #e5e7eb; } th { position: sticky; top: 0; background: #f1f5f9; font-weight: 700; white-space: nowrap; } th button { color: inherit; font: inherit; background: none; border: 0; padding: 0; text-align: left; } }
.pagination { display: flex; justify-content: space-between; gap: 16px; align-items: center; margin-top: 20px; font-size: 13px; button { padding: 8px 14px; } }
.note { margin-bottom: 24px; color: #526070; }
.page :focus-visible { outline: 3px solid #0a7859; outline-offset: 3px; }
@media (max-width: 900px) { .reports { grid-template-columns: 1fr; } .total strong { font-size: 24px; } }
@media (max-width: 600px) { .page { padding: 24px 16px; } .totals { grid-template-columns: 1fr; gap: 12px; } .total { padding: 16px; } .header h1 { font-size: 36px; } .report { padding: 16px; } .nav a { padding: 12px; } }
Loading
Loading