Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use next standalone mode #856

Open
wants to merge 8 commits into
base: dev
Choose a base branch
from
Open
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
9 changes: 9 additions & 0 deletions .slugignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
.husky
.github
.vscode
docker
docs
node_modules
public
scripts
src
4 changes: 2 additions & 2 deletions Procfile
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
clock: tsx src/cron_jobs/cron.ts
postdeploy: ./scripts/migrate.sh
clock: node .next/cli/cli.js cronjobs:start
postdeploy: node .next/cli/cli.js db:migrate
43 changes: 43 additions & 0 deletions copy-assets.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import fs from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';

// Script from https://doc.scalingo.com/languages/nodejs/nextjs-standalone
// Using the Next standalone mode, we are responsible to handle assets.
// This scripts copies all assets to the dist folder to be served by the Next server.
const dirname = path.dirname(fileURLToPath(import.meta.url));
const staticSrcPath = path.join(dirname, '.next/static');
const staticDestPath = path.join(dirname, '.next/standalone/.next/static');

const publicSrcPath = path.join(dirname, 'public');
const publicDestPath = path.join(dirname, '.next/standalone/public');

function copyAssets(src, dest) {
return fs
.mkdir(dest, { recursive: true })
.then(() => fs.readdir(src, { withFileTypes: true }))
.then((items) => {
const promises = items.map((item) => {
const srcPath = path.join(src, item.name);
const destPath = path.join(dest, item.name);

if (item.isDirectory()) {
return copyAssets(srcPath, destPath);
} else {
return fs.copyFile(srcPath, destPath);
}
});
return Promise.all(promises);
})
.catch((err) => {
console.error(`Error: ${err}`);
throw err;
});
}

const greenTick = `\x1b[32m\u2713\x1b[0m`;
const redCross = `\x1b[31m\u274C\x1b[0m`;
copyAssets(staticSrcPath, staticDestPath)
.then(() => copyAssets(publicSrcPath, publicDestPath))
.then(() => console.log(`${greenTick} Assets copied successfully`))
.catch((err) => console.error(`${redCross} Failed to copy assets: ${err}`));
10 changes: 3 additions & 7 deletions knexfile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export default {
acquireConnectionTimeout: 10000,
migrations: {
tableName: 'knex_migrations',
directory: './src/db/migrations',
directory: process.env.KNEX_MIGRATIONS_DIR ?? './src/db/migrations',
},
pool: {
idleTimeoutMillis: 10000,
Expand All @@ -19,12 +19,8 @@ export default {
},
} satisfies Knex.Config;

function addApplicationName(
connectionString: string | undefined
): string | undefined {
function addApplicationName(connectionString: string | undefined): string | undefined {
return connectionString === undefined
? undefined
: `${connectionString}${
connectionString.includes('?') ? '&' : '?'
}application_name=FCU-API`;
: `${connectionString}${connectionString.includes('?') ? '&' : '?'}application_name=FCU-API`;
}
2 changes: 2 additions & 0 deletions next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,8 @@ const securityHeadersIFramable = [
module.exports = withBundleAnalyzer(
withSentryConfig(
{
// reduce Scalingo image size (see https://doc.scalingo.com/languages/nodejs/nextjs-standalone)
output: 'standalone',
compiler: {
styledComponents: true,
},
Expand Down
7 changes: 4 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
"dev": "next dev",
"build": "next build",
"build:analyze": "ANALYZE=true yarn build",
"start": "next start -p $PORT",
"start": "node .next/standalone/server.js",
"prepare": "husky",
"prettier-check": "prettier --write src",
"prelint": "yarn prettier-check",
Expand All @@ -32,14 +32,14 @@
"db:new": "knex migrate:make",
"db:revert": "knex migrate:rollback",
"db:revert:one": "knex migrate:down",
"scalingo-postbuild": "yarn build && next-sitemap",
"scalingo-postbuild": "tsup && yarn build && node copy-assets.mjs && next-sitemap",
"predev": "only-include-used-icons",
"prebuild": "only-include-used-icons",
"talisman:add-exception": "node-talisman -i -g pre-commit"
},
"dependencies": {
"@codegouvfr/react-dsfr": "^1.11.7",
"@betagouv/france-chaleur-urbaine-publicodes": "^0.13.0",
"@codegouvfr/react-dsfr": "^1.11.7",
"@commander-js/extra-typings": "^11.1.0",
"@emotion/react": "^11.11.4",
"@emotion/server": "^11.11.0",
Expand Down Expand Up @@ -160,6 +160,7 @@
"raw-loader": "^4.0.2",
"sinon": "^15.2.0",
"ts-node": "^10.9.2",
"tsup": "^8.2.4",
"tsx": "^4.7.0",
"typescript": "5.1.6",
"vitest": "^1.0.4"
Expand Down
16 changes: 16 additions & 0 deletions scripts/cli.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { readFile } from 'fs/promises';

import { InvalidArgumentError, createCommand } from '@commander-js/extra-typings';
import { knex } from 'knex';

import { logger } from '@helpers/logger';
import knexConfig from 'knexfile';
import { startCronJobs } from 'src/cron_jobs/cron';
import db from 'src/db';
import { DatabaseTileInfo, SourceId, tilesInfo, zSourceId } from 'src/services/tiles.config';

Expand All @@ -24,6 +27,19 @@ program
await db.destroy();
});

program.command('db:migrate').action(async () => {
const db = knex(knexConfig);
const [batchNo, log] = await db.migrate.latest();
if (log.length === 0) {
console.info('Already up to date');
}
console.info(`Batch ${batchNo} run: ${log.length} migrations`);
});

program.command('cronjobs:start').action(async () => {
startCronJobs();
});

program
.command('create-modifications-reseau')
.argument('<airtable_base>', 'Base Airtable', validateKnownAirtableBase)
Expand Down
52 changes: 27 additions & 25 deletions src/cron_jobs/cron.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,34 @@ import cron from 'cron';

import { launchJob } from './launch';

new cron.CronJob({
cronTime: '00 10 * * 1-5', // du lundi au vendredi à 10:00
onTick: () => launchJob('dailyNewManagerMail'),
start: true,
timeZone: 'Europe/Paris',
});
export function startCronJobs() {
new cron.CronJob({
cronTime: '00 10 * * 1-5', // du lundi au vendredi à 10:00
onTick: () => launchJob('dailyNewManagerMail'),
start: true,
timeZone: 'Europe/Paris',
});

new cron.CronJob({
cronTime: '55 9 * * 2', // le mardi à 09:55
onTick: () => launchJob('weeklyOldManagerMail'),
start: true,
timeZone: 'Europe/Paris',
});
new cron.CronJob({
cronTime: '55 9 * * 2', // le mardi à 09:55
onTick: () => launchJob('weeklyOldManagerMail'),
start: true,
timeZone: 'Europe/Paris',
});

new cron.CronJob({
cronTime: '05 10 * * 1', // le lundi à 10:05
onTick: () => launchJob('dailyRelanceMail'),
start: true,
timeZone: 'Europe/Paris',
});
new cron.CronJob({
cronTime: '05 10 * * 1', // le lundi à 10:05
onTick: () => launchJob('dailyRelanceMail'),
start: true,
timeZone: 'Europe/Paris',
});

new cron.CronJob({
cronTime: '00 * * * *', // toutes les heures
onTick: () => launchJob('updateUsers'),
start: true,
timeZone: 'Europe/Paris',
});
new cron.CronJob({
cronTime: '00 * * * *', // toutes les heures
onTick: () => launchJob('updateUsers'),
start: true,
timeZone: 'Europe/Paris',
});

console.log('-- CRON JOB --- Started cron jobs waiting to get ticked...');
console.log('-- CRON JOB --- Started cron jobs waiting to get ticked...');
}
33 changes: 33 additions & 0 deletions tsup.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { readdirSync } from 'node:fs';
import { basename } from 'node:path';

import { defineConfig } from 'tsup';

export default defineConfig(() => {
const entry = {
cli: 'scripts/cli.ts',
};
// keep the structure
const migrationFiles = readdirSync('./src/db/migrations');
for (const filename of migrationFiles) {
entry[`migrations/${basename(filename, '.ts')}`] = `src/db/migrations/${filename}`;
}

return {
entry,
format: ['cjs'],
outDir: '.next/cli/',
bundle: true,
splitting: false,
sourcemap: false,
clean: true,
minify: true,
env: {
KNEX_MIGRATIONS_DIR: './.next/cli/migrations',
},

// include node_modules dependencies
external: [],
noExternal: ['*'],
};
});
Loading
Loading