@platformatic/watt-extra 1.19.1-alpha.1 → 1.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/watt.js CHANGED
@@ -3,6 +3,7 @@ import dns from 'node:dns/promises'
3
3
  import { readFile } from 'node:fs/promises'
4
4
  import { join, resolve } from 'node:path'
5
5
  import { createRequire } from 'node:module'
6
+ import { pathToFileURL } from 'node:url'
6
7
  import semver from 'semver'
7
8
 
8
9
  const require = createRequire(import.meta.url)
@@ -606,10 +607,11 @@ class Watt {
606
607
  }
607
608
 
608
609
  async #configureNextService (runtime, service) {
610
+ let nextPackage
609
611
  let nextSchema
610
612
 
611
613
  try {
612
- const nextPackage = createRequire(
614
+ nextPackage = createRequire(
613
615
  resolve(service.path, 'index.js')
614
616
  ).resolve('@platformatic/next')
615
617
  nextSchema = JSON.parse(
@@ -634,8 +636,12 @@ class Watt {
634
636
  'Missing required environment variables for Redis cache, not setting up HTTP next cache'
635
637
  )
636
638
  } else {
639
+ // Merging only sets the connection, keeping the cache options of the application.
640
+ // Older versions don't support the operation, so the cache options are replaced.
641
+ const op = await this.#supportsMergePatches(nextPackage) ? 'merge' : 'add'
642
+
637
643
  patches.push({
638
- op: 'add',
644
+ op,
639
645
  path: '/cache',
640
646
  value: {
641
647
  adapter: 'valkey',
@@ -662,6 +668,23 @@ class Watt {
662
668
  }
663
669
  }
664
670
 
671
+ // The patches are applied by the @platformatic/foundation used by the application
672
+ async #supportsMergePatches (nextPackage) {
673
+ try {
674
+ const basicPackage = createRequire(nextPackage).resolve('@platformatic/basic')
675
+ const foundationPackage = createRequire(basicPackage).resolve('@platformatic/foundation')
676
+ const { applyConfigPatch } = await import(pathToFileURL(foundationPackage))
677
+
678
+ return typeof applyConfigPatch === 'function'
679
+ } catch (e) {
680
+ this.#logger.warn(
681
+ { err: ensureLoggableError(e) },
682
+ 'Failed to detect the support of merge patches, replacing the Next.js cache options'
683
+ )
684
+ return false
685
+ }
686
+ }
687
+
665
688
  async #configurePlatformaticServices (runtime, app) {
666
689
  if (app.entrypoint) {
667
690
  const config = app
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@platformatic/watt-extra",
3
- "version": "1.19.1-alpha.1",
3
+ "version": "1.21.0",
4
4
  "description": "The Platformatic runtime manager",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -19,27 +19,28 @@
19
19
  },
20
20
  "devDependencies": {
21
21
  "@fastify/websocket": "^11.1.0",
22
- "@platformatic/composer": "3.71.1-alpha.0",
23
- "@platformatic/next": "3.71.1-alpha.0",
24
- "@platformatic/node": "3.71.1-alpha.0",
25
- "@platformatic/service": "3.71.1-alpha.0",
22
+ "@platformatic/composer": "^3.73.0",
23
+ "@platformatic/next": "^3.73.0",
24
+ "@platformatic/node": "^3.73.0",
25
+ "@platformatic/service": "^3.73.0",
26
26
  "atomic-sleep": "^1.0.0",
27
27
  "borp": "^1.0.0",
28
28
  "eslint": "10",
29
29
  "fastify": "^5.10.0",
30
30
  "fastify-plugin": "^6.0.0",
31
+ "iovalkey": "^0.4.0",
31
32
  "neostandard": "0.14.0-next.1",
32
33
  "next": "^16.2.10",
33
- "platformatic": "^3.71.0",
34
+ "platformatic": "^3.73.0",
34
35
  "pprof-format": "^2.1.0",
35
36
  "why-is-node-running": "^2.3.0"
36
37
  },
37
38
  "dependencies": {
38
39
  "@datadog/pprof": "^5.9.0",
39
40
  "@fastify/error": "^4.2.0",
40
- "@platformatic/foundation": "3.71.1-alpha.0",
41
- "@platformatic/runtime": "3.71.1-alpha.0",
42
- "@platformatic/wattpm-pprof-capture": "3.71.1-alpha.0",
41
+ "@platformatic/foundation": "^3.73.0",
42
+ "@platformatic/runtime": "^3.73.0",
43
+ "@platformatic/wattpm-pprof-capture": "^3.73.0",
43
44
  "avvio": "^9.1.0",
44
45
  "commist": "^3.2.0",
45
46
  "env-schema": "^8.0.0",
package/plugins/alerts.js CHANGED
@@ -130,29 +130,37 @@ async function alerts (app, _opts) {
130
130
  lastServicesAlertTime[serviceId] = currentTime
131
131
  delete healthInfo.healthConfig
132
132
 
133
- const authHeaders = await app.getAuthorizationHeaders()
134
-
135
- const { statusCode, body } = await request(`${scalerUrl}/alerts`, {
136
- method: 'POST',
137
- headers: {
138
- 'Content-Type': 'application/json',
139
- ...authHeaders
140
- },
141
- body: JSON.stringify({
142
- applicationId: app.instanceConfig?.applicationId,
143
- alert: healthInfo,
144
- healthHistory: healthCache
133
+ // This runs in a runtime event listener, where an error would be an unhandled rejection
134
+ // that stops the runtime
135
+ let alert
136
+ try {
137
+ const authHeaders = await app.getAuthorizationHeaders()
138
+
139
+ const { statusCode, body } = await request(`${scalerUrl}/alerts`, {
140
+ method: 'POST',
141
+ headers: {
142
+ 'Content-Type': 'application/json',
143
+ ...authHeaders
144
+ },
145
+ body: JSON.stringify({
146
+ applicationId: app.instanceConfig?.applicationId,
147
+ alert: healthInfo,
148
+ healthHistory: healthCache
149
+ })
145
150
  })
146
- })
147
151
 
148
- if (statusCode !== 200) {
149
- const error = await body.text()
150
- app.log.error({ error }, 'Failed to send alert to scaler')
152
+ if (statusCode !== 200) {
153
+ const error = await body.text()
154
+ app.log.error({ error }, 'Failed to send alert to scaler')
155
+ return
156
+ }
157
+
158
+ alert = await body.json()
159
+ } catch (err) {
160
+ app.log.error({ err }, 'Failed to send alert to scaler')
151
161
  return
152
162
  }
153
163
 
154
- const alert = await body.json()
155
-
156
164
  app.sendFlamegraphs({
157
165
  workerIds: [workerId],
158
166
  alertId: alert.id
@@ -7,3 +7,4 @@ allowBuilds:
7
7
  minimumReleaseAgeExclude:
8
8
  - wattpm
9
9
  - '@platformatic/*'
10
+ - 'platformatic'
@@ -364,6 +364,54 @@ test('should not fail when health info is missing', async (t) => {
364
364
  assert.strictEqual(alertReceived, null, 'No alert should have been received')
365
365
  })
366
366
 
367
+ test('should not fail when the scaler sends an invalid alert response', async (t) => {
368
+ const applicationName = 'test-app'
369
+ const applicationId = randomUUID()
370
+ const applicationPath = join(__dirname, 'fixtures', 'service-1')
371
+
372
+ let alertsReceived = 0
373
+
374
+ const icc = await startICC(t, {
375
+ applicationId,
376
+ applicationName,
377
+ // An empty response, which is not valid JSON
378
+ processAlerts: () => {
379
+ alertsReceived++
380
+ }
381
+ })
382
+
383
+ setUpEnvironment({
384
+ PLT_APP_NAME: applicationName,
385
+ PLT_APP_DIR: applicationPath,
386
+ PLT_ICC_URL: 'http://127.0.0.1:3000'
387
+ })
388
+
389
+ const app = await start()
390
+
391
+ t.after(async () => {
392
+ await app.close()
393
+ await icc.close()
394
+ })
395
+
396
+ const unhandledRejections = []
397
+ const onUnhandledRejection = (err) => unhandledRejections.push(err)
398
+ process.on('unhandledRejection', onUnhandledRejection)
399
+ t.after(() => process.removeListener('unhandledRejection', onUnhandledRejection))
400
+
401
+ emitHealthEvent(app, {
402
+ id: 'main:0',
403
+ application: 'main',
404
+ currentHealth: { elu: 0.95, heapUsed: 76798040, heapTotal: 99721216 },
405
+ unhealthy: true,
406
+ healthConfig: { enabled: true, maxELU: 0.85, maxHeapUsed: 0.99 }
407
+ })
408
+
409
+ await sleep(500)
410
+
411
+ assert.strictEqual(alertsReceived, 1)
412
+ assert.deepStrictEqual(unhandledRejections, [])
413
+ })
414
+
367
415
  test('should respect alert retention window', async (t) => {
368
416
  const applicationName = 'test-app'
369
417
  const applicationId = randomUUID()
@@ -0,0 +1,5 @@
1
+ {
2
+ "dependencies": {
3
+ "@platformatic/runtime": "workspace:*"
4
+ }
5
+ }
@@ -0,0 +1,9 @@
1
+ {
2
+ "$schema": "https://schemas.platformatic.dev/@platformatic/runtime/2.58.0.json",
3
+ "autoload": {
4
+ "path": "web"
5
+ },
6
+ "logger": {
7
+ "level": "error"
8
+ }
9
+ }
@@ -0,0 +1,2 @@
1
+ const nextConfig = {}
2
+ export default nextConfig
@@ -0,0 +1,7 @@
1
+ {
2
+ "type": "module",
3
+ "dependencies": {
4
+ "@platformatic/next": "workspace:*",
5
+ "next": "^16.2.10"
6
+ }
7
+ }
@@ -0,0 +1,8 @@
1
+ {
2
+ "$schema": "https://schemas.platformatic.dev/@platformatic/next/3.73.0-alpha.0.json",
3
+ "cache": {
4
+ "adapter": "valkey",
5
+ "url": "valkey://127.0.0.1:6390",
6
+ "cacheComponents": true
7
+ }
8
+ }
@@ -0,0 +1,7 @@
1
+ export default function RootLayout ({ children }) {
2
+ return (
3
+ <html lang='en'>
4
+ <body>{children}</body>
5
+ </html>
6
+ )
7
+ }
@@ -0,0 +1,17 @@
1
+ import { connection } from 'next/server'
2
+ import { Suspense } from 'react'
3
+ import { getMessage } from '../lib/message.js'
4
+
5
+ export default function Home () {
6
+ return (
7
+ <Suspense fallback={null}>
8
+ <Message />
9
+ </Suspense>
10
+ )
11
+ }
12
+
13
+ // Waiting for a request avoids calling the cached function during the build
14
+ async function Message () {
15
+ await connection()
16
+ return <div>{await getMessage('watt-extra')}</div>
17
+ }
@@ -0,0 +1,4 @@
1
+ export async function getMessage (name) {
2
+ 'use cache'
3
+ return `Hello ${name}`
4
+ }
@@ -4,7 +4,10 @@ import { randomUUID } from 'node:crypto'
4
4
  import { existsSync } from 'node:fs'
5
5
  import { dirname, join } from 'node:path'
6
6
  import { test } from 'node:test'
7
+ import { setTimeout as sleep } from 'node:timers/promises'
7
8
  import { fileURLToPath } from 'node:url'
9
+ import Valkey from 'iovalkey'
10
+ import { request } from 'undici'
8
11
 
9
12
  import { start } from '../index.js'
10
13
  import { setUpEnvironment, startICC } from './helper.js'
@@ -13,14 +16,11 @@ const __dirname = dirname(fileURLToPath(import.meta.url))
13
16
 
14
17
  // Matches the host port exposed by docker-compose.yml and the CI service
15
18
  const valkeyPort = 6390
19
+ const appPort = 3043
16
20
 
17
- // The runtime reports a Next.js application as '@platformatic/next' (older
18
- // runtimes said 'next'). The Next patches, cache adapter included, must be
19
- // applied in both cases.
20
- test('should configure the Next.js cache adapter for @platformatic/next applications', async (t) => {
21
+ async function startNextApp (t, fixture, applicationId) {
21
22
  const applicationName = 'test-next'
22
- const applicationId = randomUUID()
23
- const applicationPath = join(__dirname, 'fixtures', 'runtime-next')
23
+ const applicationPath = join(__dirname, 'fixtures', fixture)
24
24
 
25
25
  // The application starts in production mode, so the fixture needs a build;
26
26
  // reuse an existing one to keep local reruns fast.
@@ -57,7 +57,7 @@ test('should configure the Next.js cache adapter for @platformatic/next applicat
57
57
  PLT_APP_NAME: applicationName,
58
58
  PLT_APP_DIR: applicationPath,
59
59
  PLT_ICC_URL: icc.iccUrl,
60
- PLT_APP_PORT: 3043,
60
+ PLT_APP_PORT: appPort,
61
61
  PLT_METRICS_PORT: 9092
62
62
  })
63
63
 
@@ -68,6 +68,16 @@ test('should configure the Next.js cache adapter for @platformatic/next applicat
68
68
  await icc.close()
69
69
  })
70
70
 
71
+ return app
72
+ }
73
+
74
+ // The runtime reports a Next.js application as '@platformatic/next' (older
75
+ // runtimes said 'next'). The Next patches, cache adapter included, must be
76
+ // applied in both cases.
77
+ test('should configure the Next.js cache adapter for @platformatic/next applications', async (t) => {
78
+ const applicationId = randomUUID()
79
+ const app = await startNextApp(t, 'runtime-next', applicationId)
80
+
71
81
  const runtimeConfig = app.watt.runtime.getRuntimeConfig(true)
72
82
  const nextApplication = runtimeConfig.applications.find((application) => application.id === 'next')
73
83
  assert.strictEqual(nextApplication.type, '@platformatic/next')
@@ -80,3 +90,35 @@ test('should configure the Next.js cache adapter for @platformatic/next applicat
80
90
  maxTTL: 604800
81
91
  })
82
92
  })
93
+
94
+ // The fixture enables the Cache Components in its own cache options, which must
95
+ // survive the patch that sets the Valkey connection
96
+ test('should keep the cache options of @platformatic/next applications', async (t) => {
97
+ const applicationId = randomUUID()
98
+ const app = await startNextApp(t, 'runtime-next-components', applicationId)
99
+
100
+ const nextConfig = await app.watt.runtime.getApplicationConfig('next')
101
+ assert.deepStrictEqual(nextConfig.cache, {
102
+ adapter: 'valkey',
103
+ url: `valkey://cache-user:cache-pass@127.0.0.1:${valkeyPort}`,
104
+ prefix: `${applicationId}:`,
105
+ maxTTL: 604800,
106
+ cacheComponents: true
107
+ })
108
+
109
+ const { statusCode, body } = await request(`http://127.0.0.1:${appPort}/`)
110
+ assert.strictEqual(statusCode, 200)
111
+ assert.match(await body.text(), /Hello watt-extra/)
112
+
113
+ // The "use cache" entry is stored in Valkey, under the prefix set by watt-extra
114
+ const valkey = new Valkey(`valkey://cache-user:cache-pass@127.0.0.1:${valkeyPort}`)
115
+ t.after(() => valkey.quit())
116
+
117
+ let keys = []
118
+ for (const deadline = Date.now() + 5000; !keys.length && Date.now() < deadline;) {
119
+ await sleep(100)
120
+ keys = await valkey.keys(`${applicationId}::cache:next:*:components:values:*`)
121
+ }
122
+
123
+ assert.strictEqual(keys.length, 1)
124
+ })
@@ -1,24 +0,0 @@
1
- {
2
- "permissions": {
3
- "allow": [
4
- "Read(//work/workspaces/workspace-platformatic/platformatic/**)",
5
- "Bash(npx borp:*)",
6
- "Bash(timeout 30 npx borp -c 1 --timeout=20000 ./test/trigger-flamegraphs.test.js)",
7
- "Bash(xargs cat:*)",
8
- "Bash(pnpm install)",
9
- "Bash(find:*)",
10
- "Bash(cat:*)",
11
- "WebFetch(domain:github.com)",
12
- "Bash(node --test:*)",
13
- "Bash(for i in 1 2 3)",
14
- "Bash(do echo \"Run $i:\")",
15
- "Bash(done)",
16
- "Bash(git stash:*)",
17
- "Bash(echo:*)",
18
- "Bash(grep:*)",
19
- "Bash(gh api:*)"
20
- ],
21
- "deny": [],
22
- "ask": []
23
- }
24
- }