@platformatic/next 2.17.0 → 2.19.0-alpha.1

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/config.d.ts CHANGED
@@ -93,4 +93,10 @@ export interface PlatformaticNextJsStackable {
93
93
  production?: string;
94
94
  };
95
95
  };
96
+ cache?: {
97
+ adapter: "redis" | "valkey";
98
+ url: string;
99
+ prefix?: string;
100
+ maxTTL?: number | string;
101
+ };
96
102
  }
package/index.js CHANGED
@@ -59,8 +59,10 @@ export class NextStackable extends BaseStackable {
59
59
  return this.stopCommand()
60
60
  }
61
61
 
62
+ globalThis.platformatic.events.emit('plt:next:close')
63
+
62
64
  if (this.isProduction) {
63
- return new Promise((resolve, reject) => {
65
+ await new Promise((resolve, reject) => {
64
66
  this.#server.close(error => {
65
67
  /* c8 ignore next 3 */
66
68
  if (error) {
@@ -70,6 +72,8 @@ export class NextStackable extends BaseStackable {
70
72
  resolve()
71
73
  })
72
74
  })
75
+
76
+ await this.childManager.close()
73
77
  } else {
74
78
  const exitPromise = once(this.#child, 'exit')
75
79
  await this.childManager.close()
@@ -96,7 +100,8 @@ export class NextStackable extends BaseStackable {
96
100
  /* c8 ignore next 5 */
97
101
  async getWatchConfig () {
98
102
  return {
99
- enabled: false
103
+ enabled: false,
104
+ path: this.root
100
105
  }
101
106
  }
102
107
 
@@ -131,6 +136,7 @@ export class NextStackable extends BaseStackable {
131
136
  this.childManager = new ChildManager({
132
137
  loader: loaderUrl,
133
138
  context: {
139
+ config: this.configManager.current,
134
140
  serviceId: this.serviceId,
135
141
  workerId: this.workerId,
136
142
  // Always use URL to avoid serialization problem in Windows
@@ -183,6 +189,7 @@ export class NextStackable extends BaseStackable {
183
189
  this.childManager = new ChildManager({
184
190
  loader: loaderUrl,
185
191
  context: {
192
+ config: this.configManager.current,
186
193
  serviceId: this.serviceId,
187
194
  workerId: this.workerId,
188
195
  // Always use URL to avoid serialization problem in Windows
@@ -202,6 +209,7 @@ export class NextStackable extends BaseStackable {
202
209
 
203
210
  async #startProductionNext () {
204
211
  try {
212
+ globalThis.platformatic.config = this.configManager.current
205
213
  await this.childManager.inject()
206
214
  const { nextStart } = await importFile(pathResolve(this.#next, './dist/cli/next-start.js'))
207
215
 
@@ -242,6 +250,10 @@ function transformConfig () {
242
250
  this.current.watch = { enabled: this.current.watch || false }
243
251
  }
244
252
 
253
+ if (this.current.cache?.adapter === 'redis') {
254
+ this.current.cache.adapter = 'valkey'
255
+ }
256
+
245
257
  basicTransformConfig.call(this)
246
258
  }
247
259
 
@@ -0,0 +1,210 @@
1
+ import { ensureLoggableError } from '@platformatic/utils'
2
+ import { Redis } from 'iovalkey'
3
+ import { pack, unpack } from 'msgpackr'
4
+ import { existsSync, readFileSync } from 'node:fs'
5
+ import { hostname } from 'node:os'
6
+ import { resolve } from 'node:path'
7
+ import { fileURLToPath } from 'node:url'
8
+ import { pino } from 'pino'
9
+
10
+ export const MAX_BATCH_SIZE = 100
11
+
12
+ const sections = {
13
+ values: 'values',
14
+ tags: 'tags'
15
+ }
16
+
17
+ export function keyFor (prefix, subprefix, section, key) {
18
+ return [prefix, 'cache:next', subprefix, section, key ? Buffer.from(key).toString('base64url') : undefined]
19
+ .filter(c => c)
20
+ .join(':')
21
+ }
22
+
23
+ export class CacheHandler {
24
+ #config
25
+ #logger
26
+ #store
27
+ #subprefix
28
+ #maxTTL
29
+
30
+ constructor () {
31
+ this.#logger = this.#createLogger()
32
+ this.#config = globalThis.platformatic.config.cache
33
+ this.#store = new Redis(this.#config.url, { enableAutoPipelining: true })
34
+ this.#maxTTL = this.#config.maxTTL
35
+ this.#subprefix = this.#getSubprefix()
36
+
37
+ // Handle disconnection not to hang the process on exit
38
+ globalThis.platformatic.events.on('plt:next:close', () => {
39
+ this.#store.disconnect(false)
40
+ })
41
+ }
42
+
43
+ async get (cacheKey) {
44
+ this.#logger.trace({ key: cacheKey }, 'get')
45
+
46
+ const key = this.#keyFor(cacheKey, sections.values)
47
+
48
+ let rawValue
49
+ try {
50
+ rawValue = await this.#store.get(key)
51
+
52
+ if (!rawValue) {
53
+ return
54
+ }
55
+ } catch (e) {
56
+ this.#logger.error({ err: ensureLoggableError(e) }, 'Cannot read cache value from Valkey')
57
+ throw new Error('Cannot read cache value from Valkey', { cause: e })
58
+ }
59
+
60
+ let value
61
+ try {
62
+ value = this.#deserialize(rawValue)
63
+ } catch (e) {
64
+ this.#logger.error({ err: ensureLoggableError(e) }, 'Cannot deserialize cache value from Valkey')
65
+
66
+ // Avoid useless reads the next time
67
+ // Note that since the value was unserializable, we don't know its tags and thus
68
+ // we cannot remove it from the tags sets. TTL will take care of them.
69
+ await this.#store.del(key)
70
+
71
+ throw new Error('Cannot deserialize cache value from Valkey', { cause: e })
72
+ }
73
+
74
+ if (this.#maxTTL < value.revalidate) {
75
+ try {
76
+ await this.#refreshKey(key, value)
77
+ } catch (e) {
78
+ this.#logger.error({ err: ensureLoggableError(e) }, 'Cannot refresh cache key expiration in Valkey')
79
+
80
+ // We don't throw here since we want to use the cached value anyway
81
+ }
82
+ }
83
+
84
+ return value
85
+ }
86
+
87
+ async set (cacheKey, value, { tags, revalidate }) {
88
+ this.#logger.trace({ key: cacheKey, value, tags, revalidate }, 'set')
89
+
90
+ try {
91
+ // Compute the parameters to save
92
+ const key = this.#keyFor(cacheKey, sections.values)
93
+ const data = this.#serialize({ value, tags, lastModified: Date.now(), revalidate, maxTTL: this.#maxTTL })
94
+ const expire = Math.min(revalidate, this.#maxTTL)
95
+
96
+ // Enqueue all the operations to perform in Valkey
97
+ const promises = []
98
+ promises.push(this.#store.set(key, data, 'EX', expire))
99
+
100
+ // As Next.js limits tags to 64, we don't need to manage batches here
101
+ if (Array.isArray(tags)) {
102
+ for (const tag of tags) {
103
+ const tagsKey = this.#keyFor(tag, sections.tags)
104
+ promises.push(this.#store.sadd(tagsKey, key))
105
+ promises.push(this.#store.expire(tagsKey, expire))
106
+ }
107
+ }
108
+
109
+ // Execute all the operations
110
+ await Promise.all(promises)
111
+ } catch (e) {
112
+ this.#logger.error({ err: ensureLoggableError(e) }, 'Cannot write cache value in Valkey')
113
+ throw new Error('Cannot write cache value in Valkey', { cause: e })
114
+ }
115
+ }
116
+
117
+ async revalidateTag (tags) {
118
+ this.#logger.trace({ tags }, 'revalidateTag')
119
+
120
+ if (typeof tags === 'string') {
121
+ tags = [tags]
122
+ }
123
+
124
+ try {
125
+ let promises = []
126
+
127
+ for (const tag of tags) {
128
+ const tagsKey = this.#keyFor(tag, sections.tags)
129
+
130
+ // For each key in the tag set, expire the key
131
+ for await (const keys of this.#store.sscanStream(tagsKey)) {
132
+ for (const key of keys) {
133
+ promises.push(this.#store.del(key))
134
+
135
+ // Batch full, execute it
136
+ if (promises.length >= MAX_BATCH_SIZE) {
137
+ await Promise.all(promises)
138
+ promises = []
139
+ }
140
+ }
141
+ }
142
+
143
+ // Delete the set, this will also take care of executing pending operation for a non full batch
144
+ promises.push(this.#store.del(tagsKey))
145
+ await Promise.all(promises)
146
+ promises = []
147
+ }
148
+ } catch (e) {
149
+ this.#logger.error({ err: ensureLoggableError(e) }, 'Cannot expire cache tags in Valkey')
150
+ throw new Error('Cannot expire cache tags in Valkey', { cause: e })
151
+ }
152
+ }
153
+
154
+ async #refreshKey (key, value) {
155
+ const life = Math.round((Date.now() - value.lastModified) / 1000)
156
+ const expire = Math.min(value.revalidate - life, this.#maxTTL)
157
+
158
+ if (expire > 0) {
159
+ const promises = []
160
+ promises.push(this.#store.expire(key, expire, 'gt'))
161
+
162
+ if (Array.isArray(value.tags)) {
163
+ for (const tag of value.tags) {
164
+ const tagsKey = this.#keyFor(tag, sections.tags)
165
+ promises.push(this.#store.expire(tagsKey, expire, 'gt'))
166
+ }
167
+ }
168
+
169
+ await Promise.all(promises)
170
+ }
171
+ }
172
+
173
+ #createLogger () {
174
+ const pinoOptions = {
175
+ level: globalThis.platformatic?.logLevel ?? 'info'
176
+ }
177
+
178
+ if (this.serviceId) {
179
+ pinoOptions.name = `cache:${this.serviceId}`
180
+ }
181
+
182
+ if (typeof globalThis.platformatic.workerId !== 'undefined') {
183
+ pinoOptions.base = { pid: process.pid, hostname: hostname(), worker: this.workerId }
184
+ }
185
+
186
+ return pino(pinoOptions)
187
+ }
188
+
189
+ #getSubprefix () {
190
+ const root = fileURLToPath(globalThis.platformatic.root)
191
+
192
+ return existsSync(resolve(root, '.next/BUILD_ID'))
193
+ ? (this.#subprefix = readFileSync(resolve(root, '.next/BUILD_ID'), 'utf-8').trim())
194
+ : 'development'
195
+ }
196
+
197
+ #keyFor (key, section) {
198
+ return keyFor(this.#config.prefix, this.#subprefix, section, key)
199
+ }
200
+
201
+ #serialize (data) {
202
+ return pack(data).toString('base64url')
203
+ }
204
+
205
+ #deserialize (data) {
206
+ return unpack(Buffer.from(data, 'base64url'))
207
+ }
208
+ }
209
+
210
+ export default CacheHandler
package/lib/loader.js CHANGED
@@ -11,10 +11,12 @@ import {
11
11
  variableDeclarator
12
12
  } from '@babel/types'
13
13
  import { readFile, realpath } from 'node:fs/promises'
14
+ import { sep } from 'node:path'
14
15
  import { fileURLToPath, pathToFileURL } from 'node:url'
15
16
 
16
17
  const originalId = '__pltOriginalNextConfig'
17
18
 
19
+ let config
18
20
  let candidates
19
21
  let basePath
20
22
 
@@ -35,6 +37,11 @@ function parseSingleExpression (expr) {
35
37
  __pltOriginalNextConfig.basePath = basePath
36
38
  }
37
39
 
40
+ if(typeof __pltOriginalNextConfig.cacheHandler === 'undefined') {
41
+ __pltOriginalNextConfig.cacheHandler = $PATH
42
+ __pltOriginalNextConfig.cacheMaxMemorySize = 0
43
+ }
44
+
38
45
  // This is to send the configuraion when Next is executed in a child process (development)
39
46
  globalThis[Symbol.for('plt.children.itc')]?.notify('config', __pltOriginalNextConfig)
40
47
 
@@ -45,21 +52,35 @@ function parseSingleExpression (expr) {
45
52
  }
46
53
  */
47
54
  function createEvaluatorWrapperFunction (original) {
55
+ const cacheHandler = config?.cache
56
+ ? fileURLToPath(new URL(`./caching/${config.cache.adapter ?? 'foo'}.js`, import.meta.url)).replaceAll(sep, '/')
57
+ : undefined
58
+
48
59
  return functionDeclaration(
49
60
  null,
50
61
  [restElement(identifier('args'))],
51
- blockStatement([
52
- variableDeclaration('let', [variableDeclarator(identifier(originalId), original)]),
53
- parseSingleExpression(
54
- `if (typeof ${originalId} === 'function') { ${originalId} = await ${originalId}(...args) }`
55
- ),
56
- parseSingleExpression(
57
- `if (typeof ${originalId}.basePath === 'undefined') { ${originalId}.basePath = "${basePath}" }`
58
- ),
59
- parseSingleExpression(`globalThis[Symbol.for('plt.children.itc')]?.notify('config', ${originalId})`),
60
- parseSingleExpression(`process.emit('plt:next:config', ${originalId})`),
61
- returnStatement(identifier(originalId))
62
- ]),
62
+ blockStatement(
63
+ [
64
+ variableDeclaration('let', [variableDeclarator(identifier(originalId), original)]),
65
+ parseSingleExpression(
66
+ `if (typeof ${originalId} === 'function') { ${originalId} = await ${originalId}(...args) }`
67
+ ),
68
+ parseSingleExpression(
69
+ `if (typeof ${originalId}.basePath === 'undefined') { ${originalId}.basePath = "${basePath}" }`
70
+ ),
71
+ cacheHandler
72
+ ? parseSingleExpression(`
73
+ if (typeof ${originalId}.cacheHandler === 'undefined') {
74
+ ${originalId}.cacheHandler = '${cacheHandler}'
75
+ ${originalId}.cacheMaxMemorySize = 0
76
+ }
77
+ `)
78
+ : undefined,
79
+ parseSingleExpression(`globalThis[Symbol.for('plt.children.itc')]?.notify('config', ${originalId})`),
80
+ parseSingleExpression(`process.emit('plt:next:config', ${originalId})`),
81
+ returnStatement(identifier(originalId))
82
+ ].filter(e => e)
83
+ ),
63
84
  false,
64
85
  true
65
86
  )
@@ -125,6 +146,7 @@ export async function initialize (data) {
125
146
  // Keep in sync with https://github.com/vercel/next.js/blob/main/packages/next/src/shared/lib/constants.ts
126
147
  candidates = ['next.config.js', 'next.config.mjs'].map(c => new URL(c, realRoot).toString())
127
148
  basePath = data.basePath ?? ''
149
+ config = data.config
128
150
  }
129
151
 
130
152
  export async function load (url, context, nextLoad) {
package/lib/schema.js CHANGED
@@ -4,6 +4,36 @@ import { readFileSync } from 'node:fs'
4
4
 
5
5
  export const packageJson = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf-8'))
6
6
 
7
+ export const cache = {
8
+ type: 'object',
9
+ properties: {
10
+ adapter: {
11
+ type: 'string',
12
+ enum: ['redis', 'valkey']
13
+ },
14
+ url: {
15
+ type: 'string'
16
+ },
17
+ prefix: {
18
+ type: 'string'
19
+ },
20
+ maxTTL: {
21
+ default: 86400 * 7, // One week
22
+ anyOf: [
23
+ {
24
+ type: 'number',
25
+ minimum: 0
26
+ },
27
+ {
28
+ type: 'string'
29
+ }
30
+ ]
31
+ }
32
+ },
33
+ required: ['adapter', 'url'],
34
+ additionalProperties: false
35
+ }
36
+
7
37
  export const schema = {
8
38
  $id: `https://schemas.platformatic.dev/@platformatic/next/${packageJson.version}.json`,
9
39
  $schema: 'http://json-schema.org/draft-07/schema#',
@@ -16,7 +46,8 @@ export const schema = {
16
46
  logger: utilsSchemaComponents.logger,
17
47
  server: utilsSchemaComponents.server,
18
48
  watch: schemaComponents.watch,
19
- application: schemaComponents.application
49
+ application: schemaComponents.application,
50
+ cache
20
51
  },
21
52
  additionalProperties: false
22
53
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@platformatic/next",
3
- "version": "2.17.0",
3
+ "version": "2.19.0-alpha.1",
4
4
  "description": "Platformatic Next.js Stackable",
5
5
  "main": "index.js",
6
6
  "type": "module",
@@ -19,10 +19,12 @@
19
19
  "@babel/parser": "^7.25.3",
20
20
  "@babel/traverse": "^7.25.3",
21
21
  "@babel/types": "^7.25.2",
22
+ "iovalkey": "^0.2.1",
23
+ "msgpackr": "^1.11.2",
22
24
  "semver": "^7.6.3",
23
- "@platformatic/basic": "2.17.0",
24
- "@platformatic/utils": "2.17.0",
25
- "@platformatic/config": "2.17.0"
25
+ "@platformatic/basic": "2.19.0-alpha.1",
26
+ "@platformatic/config": "2.19.0-alpha.1",
27
+ "@platformatic/utils": "2.19.0-alpha.1"
26
28
  },
27
29
  "devDependencies": {
28
30
  "@fastify/reply-from": "^11.0.0",
@@ -36,8 +38,8 @@
36
38
  "react-dom": "^18.3.1",
37
39
  "typescript": "^5.5.4",
38
40
  "ws": "^8.18.0",
39
- "@platformatic/composer": "2.17.0",
40
- "@platformatic/service": "2.17.0"
41
+ "@platformatic/composer": "2.19.0-alpha.1",
42
+ "@platformatic/service": "2.19.0-alpha.1"
41
43
  },
42
44
  "scripts": {
43
45
  "test": "npm run lint && borp --concurrency=1 --no-timeout",
package/schema.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "$id": "https://schemas.platformatic.dev/@platformatic/next/2.17.0.json",
2
+ "$id": "https://schemas.platformatic.dev/@platformatic/next/2.19.0-alpha.1.json",
3
3
  "$schema": "http://json-schema.org/draft-07/schema#",
4
4
  "title": "Platformatic Next.js Stackable",
5
5
  "type": "object",
@@ -296,6 +296,41 @@
296
296
  },
297
297
  "additionalProperties": false,
298
298
  "default": {}
299
+ },
300
+ "cache": {
301
+ "type": "object",
302
+ "properties": {
303
+ "adapter": {
304
+ "type": "string",
305
+ "enum": [
306
+ "redis",
307
+ "valkey"
308
+ ]
309
+ },
310
+ "url": {
311
+ "type": "string"
312
+ },
313
+ "prefix": {
314
+ "type": "string"
315
+ },
316
+ "maxTTL": {
317
+ "default": 604800,
318
+ "anyOf": [
319
+ {
320
+ "type": "number",
321
+ "minimum": 0
322
+ },
323
+ {
324
+ "type": "string"
325
+ }
326
+ ]
327
+ }
328
+ },
329
+ "required": [
330
+ "adapter",
331
+ "url"
332
+ ],
333
+ "additionalProperties": false
299
334
  }
300
335
  },
301
336
  "additionalProperties": false