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
15 changes: 13 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ jobs:

- name: Validate production deployment
run: |
scripts/test-public-health.sh
scripts/test-deploy-classifier.sh
scripts/test-deploy.sh
scripts/test-image-deploy.sh
Expand Down Expand Up @@ -117,6 +118,9 @@ jobs:
PGDATABASE: letscube
PGUSER: letscube
PGPASSWORD: letscube
CORS_ORIGINS: http://localhost:3000,http://localhost:8080
LETSCUBE_TEST_AUTH: true
SOCIAL_FEATURES_ENABLED: true
services:
postgres:
image: postgres:17-alpine
Expand Down Expand Up @@ -160,10 +164,15 @@ jobs:
run: yarn workspace letscube-server postgres:migrate

- name: Start server
run: CORS_ORIGINS=http://localhost:3000,http://localhost:8080 LETSCUBE_TEST_AUTH=true SOCIAL_FEATURES_ENABLED=true yarn workspace letscube-server node index.js > server.log 2>&1 &
run: |
mkdir -p .tmp
node server/index.js > server.log 2>&1 &
echo $! > .tmp/ci-api.pid

- name: Start socket server
run: SOCIAL_FEATURES_ENABLED=true yarn workspace letscube-server node socket/ > socket.log 2>&1 &
run: |
node server/socket/index.js > socket.log 2>&1 &
echo $! > .tmp/ci-socket.pid

- name: Wait for local stack
run: |
Expand Down Expand Up @@ -194,6 +203,8 @@ jobs:
done

- name: Run Cypress
env:
CYPRESS_faultInjection: true
run: yarn cypress:run

- name: Print app logs on failure
Expand Down
66 changes: 66 additions & 0 deletions .github/workflows/production-health.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
name: Production health monitor

on:
schedule:
- cron: '*/5 * * * *'
workflow_dispatch:

permissions:
contents: read
issues: write

concurrency:
group: production-health-monitor
cancel-in-progress: true

jobs:
monitor:
name: Verify public production health
runs-on: ubuntu-24.04
timeout-minutes: 5
steps:
- name: Check out repository
uses: actions/checkout@v4

- name: Verify public routes
id: health
continue-on-error: true
run: scripts/check-public-health.sh

- name: Open one outage issue
if: steps.health.outcome == 'failure'
env:
GH_TOKEN: ${{ github.token }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
label=production-health
gh label create "$label" \
--color D73A4A \
--description "The external production health monitor found an outage." \
--force
issue_number="$(gh issue list --state open --label "$label" --json number --jq '.[0].number // empty')"
if [ -z "$issue_number" ]; then
gh issue create \
--label "$label" \
--title "Production health monitor failed" \
--body "The external monitor could not verify the homepage and both health endpoints. [Open the failed run]($RUN_URL)."
fi

- name: Close the outage issue after recovery
if: steps.health.outcome == 'success'
env:
GH_TOKEN: ${{ github.token }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
label_count="$(gh label list --json name --jq 'map(select(.name == "production-health")) | length')"
if [ "$label_count" -gt 0 ]; then
issue_number="$(gh issue list --state open --label production-health --json number --jq '.[0].number // empty')"
if [ -n "$issue_number" ]; then
gh issue close "$issue_number" \
--comment "The external monitor reports that production recovered. [Open the successful run]($RUN_URL)."
fi
fi

- name: Fail an unhealthy monitor run
if: steps.health.outcome == 'failure'
run: exit 1
46 changes: 46 additions & 0 deletions client/src/components/ErrorBoundary.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import React from 'react';
import PropTypes from 'prop-types';

class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { failed: false };
}

static getDerivedStateFromError() {
return { failed: true };
}

componentDidCatch(error, details) {
this.props.reportError(error, details);
}

render() {
if (!this.state.failed) {
return this.props.children;
}

return (
<main role="alert" style={{ margin: '4rem auto', maxWidth: '32rem', padding: '1rem' }}>
<h1>Let&apos;s Cube stopped unexpectedly.</h1>
<p>If you have a saved result, it remains on this device. Reload the app to recover.</p>
<button type="button" onClick={this.props.onReload}>Reload app</button>
</main>
);
}
}

ErrorBoundary.propTypes = {
children: PropTypes.node.isRequired,
onReload: PropTypes.func,
reportError: PropTypes.func,
};

ErrorBoundary.defaultProps = {
onReload: () => window.location.reload(),
// The browser console is the only error sink configured in this client.
// eslint-disable-next-line no-console
reportError: (error, details) => console.error(error, details),
};

export default ErrorBoundary;
23 changes: 23 additions & 0 deletions client/src/components/ErrorBoundary.test.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import React from 'react';
import { fireEvent, render, screen } from '@testing-library/react';
import ErrorBoundary from './ErrorBoundary';

const Broken = () => {
throw new Error('render failed');
};

it('offers a reload action after a render failure', () => {
const onReload = jest.fn();
const reportError = jest.fn();

render(
<ErrorBoundary onReload={onReload} reportError={reportError}>
<Broken />
</ErrorBoundary>,
);

expect(screen.getByRole('alert')).toHaveTextContent("Let's Cube stopped unexpectedly.");
expect(reportError).toHaveBeenCalledWith(expect.any(Error), expect.any(Object));
fireEvent.click(screen.getByRole('button', { name: 'Reload app' }));
expect(onReload).toHaveBeenCalledTimes(1);
});
10 changes: 8 additions & 2 deletions client/src/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ import React from 'react';
import { createRoot } from 'react-dom/client';
import './css/index.css';
import App from './components/App';
import ErrorBoundary from './components/ErrorBoundary';
import * as serviceWorker from './registerServiceWorker';
import { promptForAppUpdate } from './lib/appUpdate';
import store from './store';
import { connectSocket as connectToDefault } from './store/default/actions';
import { connectSocket as connectToRooms } from './store/rooms/actions';
Expand All @@ -14,8 +16,12 @@ store.dispatch(fetchUser());

/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */
const root = createRoot(document.querySelector('#root'));
root.render(<App />);
root.render(
<ErrorBoundary>
<App />
</ErrorBoundary>,
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
serviceWorker.register();
serviceWorker.register({ onUpdate: promptForAppUpdate });
14 changes: 14 additions & 0 deletions client/src/lib/appUpdate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const UPDATE_MESSAGE = 'A new version of Let\'s Cube is ready. Reload now?';

export const promptForAppUpdate = (
applyUpdate,
confirmUpdate = (message) => window.confirm(message),
) => {
if (confirmUpdate(UPDATE_MESSAGE)) {
applyUpdate();
return true;
}
return false;
};

export { UPDATE_MESSAGE };
17 changes: 17 additions & 0 deletions client/src/lib/appUpdate.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { promptForAppUpdate, UPDATE_MESSAGE } from './appUpdate';

it('applies a waiting update after user approval', () => {
const applyUpdate = jest.fn();
const confirmUpdate = jest.fn().mockReturnValue(true);

expect(promptForAppUpdate(applyUpdate, confirmUpdate)).toBe(true);
expect(confirmUpdate).toHaveBeenCalledWith(UPDATE_MESSAGE);
expect(applyUpdate).toHaveBeenCalledTimes(1);
});

it('keeps the current client after user rejection', () => {
const applyUpdate = jest.fn();

expect(promptForAppUpdate(applyUpdate, () => false)).toBe(false);
expect(applyUpdate).not.toHaveBeenCalled();
});
30 changes: 28 additions & 2 deletions client/src/lib/fetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,37 @@
export const apiOrigin = process.env.REACT_APP_API_ORIGIN;

const UNSAFE_METHODS = new Set(['DELETE', 'PATCH', 'POST', 'PUT']);
const DEFAULT_TIMEOUT_MS = 15000;
let csrfTokenRequest;

export const fetchWithTimeout = async (url, options = {}, timeoutMs = DEFAULT_TIMEOUT_MS) => {
const controller = new AbortController();
const upstreamSignal = options.signal;
const abortFromUpstream = () => controller.abort(upstreamSignal.reason);
if (upstreamSignal) {
if (upstreamSignal.aborted) {
abortFromUpstream();
} else {
upstreamSignal.addEventListener('abort', abortFromUpstream, { once: true });
}
}
const timeout = setTimeout(() => {
controller.abort(new Error('Request timed out.'));
}, timeoutMs);

try {
return await fetch(url, { ...options, signal: controller.signal });
} finally {
clearTimeout(timeout);
if (upstreamSignal) {
upstreamSignal.removeEventListener('abort', abortFromUpstream);
}
}
};

const requestCsrfToken = async () => {
if (!csrfTokenRequest) {
csrfTokenRequest = fetch(`${apiOrigin}/api/csrf-token`, {
csrfTokenRequest = fetchWithTimeout(`${apiOrigin}/api/csrf-token`, {
credentials: 'include',
}).then(async (response) => {
if (!response.ok) {
Expand Down Expand Up @@ -38,7 +64,7 @@ export const lcFetch = async (url, options = {}) => {
const method = (options.method || 'GET').toUpperCase();
const csrfToken = UNSAFE_METHODS.has(method) ? await requestCsrfToken() : null;

return fetch(`${apiOrigin}${url}`, {
return fetchWithTimeout(`${apiOrigin}${url}`, {
...options,
credentials: 'include',
...(csrfToken ? { headers: withCsrfToken(options.headers, csrfToken) } : {}),
Expand Down
Loading
Loading