-
Notifications
You must be signed in to change notification settings - Fork 9
feat(generator): add node.config.json
#253
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
Closed
Closed
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
f9c1321
feat(generator): add `node.config.json`
avivkeller 27fe5d1
move schema to json, use function for type mapping
avivkeller be60acf
resolve reviews
avivkeller 14f3c5f
fixup! resolve reviews
avivkeller 928b380
resolve reviews
avivkeller File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
// Error Messages | ||
export const ERRORS = { | ||
missingCCandHFiles: | ||
'Both node_options.cc and node_options.h must be provided.', | ||
headerTypeNotFound: | ||
'A type for "{{headerKey}}" not found in the header file.', | ||
missingTypeDefinition: 'No type schema found for "{{type}}".', | ||
}; | ||
|
||
// Regex pattern to match calls to the AddOption function. | ||
export const ADD_OPTION_REGEX = | ||
/AddOption[\s\n\r]*\([\s\n\r]*"([^"]+)"(.*?)\);/gs; | ||
|
||
// Regex pattern to match header keys in the Options class. | ||
export const OPTION_HEADER_KEY_REGEX = /Options::(\w+)/; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,96 @@ | ||
import { readFile, writeFile } from 'node:fs/promises'; | ||
import { join } from 'node:path'; | ||
|
||
import { | ||
ADD_OPTION_REGEX, | ||
ERRORS, | ||
OPTION_HEADER_KEY_REGEX, | ||
} from './constants.mjs'; | ||
import schema from './schema.json' with { type: 'json' }; | ||
import { formatErrorMessage, getTypeSchema } from './utilities.mjs'; | ||
|
||
/** | ||
* This generator generates the `node.config.json` schema. | ||
* | ||
* @typedef {Array<ApiDocMetadataEntry>} Input | ||
* | ||
* @type {GeneratorMetadata<Input, string>} | ||
*/ | ||
export default { | ||
name: 'node-config-schema', | ||
|
||
version: '1.0.0', | ||
|
||
description: 'Generates the node.config.json schema.', | ||
|
||
/** | ||
* Generates the `node.config.json` schema. | ||
* @param {unknown} _ - Unused parameter | ||
* @param {Partial<GeneratorOptions>} options - Options containing the input file paths | ||
* @throws {Error} If the required files node_options.cc or node_options.h are missing or invalid. | ||
*/ | ||
async generate(_, options) { | ||
// Ensure input files are provided and capture the paths | ||
const ccFile = options.input.find(filePath => | ||
filePath.endsWith('node_options.cc') | ||
); | ||
const hFile = options.input.find(filePath => | ||
filePath.endsWith('node_options.h') | ||
); | ||
|
||
// Error handling if either cc or h file is missing | ||
if (!ccFile || !hFile) { | ||
throw new Error(ERRORS.missingCCandHFiles); | ||
ovflowd marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
// Read the contents of the cc and h files | ||
const ccContent = await readFile(ccFile, 'utf-8'); | ||
const hContent = await readFile(hFile, 'utf-8'); | ||
|
||
const { nodeOptions } = schema.properties; | ||
|
||
// Process the cc content and match AddOption calls | ||
for (const [, option, config] of ccContent.matchAll(ADD_OPTION_REGEX)) { | ||
// If config doesn't include 'kAllowedInEnvvar', skip this option | ||
if (!config.includes('kAllowedInEnvvar')) { | ||
continue; | ||
} | ||
|
||
const headerKey = config.match(OPTION_HEADER_KEY_REGEX)?.[1]; | ||
avivkeller marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
// If there's no header key, it's either a V8 option or a no-op | ||
if (!headerKey) { | ||
continue; | ||
} | ||
|
||
// Try to find the corresponding header type in the hContent | ||
const headerTypeMatch = hContent.match( | ||
new RegExp(`\\s*(.+)\\s${headerKey}[^\\B_]`) | ||
); | ||
|
||
if (!headerTypeMatch) { | ||
throw new Error( | ||
formatErrorMessage(ERRORS.headerTypeNotFound, { headerKey }) | ||
); | ||
} | ||
|
||
// Add the option to the schema after removing the '--' prefix | ||
nodeOptions.properties[option.replace('--', '')] = getTypeSchema( | ||
headerTypeMatch[1].trim() | ||
); | ||
} | ||
|
||
nodeOptions.properties = Object.fromEntries( | ||
Object.keys(nodeOptions.properties) | ||
.sort() | ||
.map(key => [key, nodeOptions.properties[key]]) | ||
); | ||
|
||
await writeFile( | ||
join(options.output, 'node-config-schema.json'), | ||
JSON.stringify(schema, null, 2) + '\n' | ||
); | ||
|
||
return schema; | ||
}, | ||
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
{ | ||
"$schema": "https://json-schema.org/draft/2020-12/schema", | ||
"additionalProperties": false, | ||
"properties": { | ||
"$schema": { | ||
"type": "string" | ||
}, | ||
"nodeOptions": { | ||
"additionalProperties": false, | ||
"properties": {}, | ||
"type": "object" | ||
} | ||
}, | ||
"type": "object" | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
import { ERRORS } from './constants.mjs'; | ||
|
||
/** | ||
* Helper function to replace placeholders in error messages with dynamic values. | ||
* @param {string} message - The error message with placeholders. | ||
* @param {Object} params - The values to replace the placeholders. | ||
* @returns {string} - The formatted error message. | ||
*/ | ||
export function formatErrorMessage(message, params) { | ||
return message.replace(/{{(\w+)}}/g, (_, key) => params[key] || `{{${key}}}`); | ||
} | ||
|
||
/** | ||
* Returns the JSON Schema definition for a given C++ type. | ||
* | ||
* @param {string} type - The type to get the schema for. | ||
* @returns {object} JSON Schema definition for the given type. | ||
*/ | ||
export function getTypeSchema(type) { | ||
switch (type) { | ||
case 'std::vector<std::string>': | ||
return { | ||
oneOf: [ | ||
{ type: 'string' }, | ||
{ | ||
type: 'array', | ||
items: { type: 'string' }, | ||
minItems: 1, | ||
}, | ||
], | ||
}; | ||
case 'uint64_t': | ||
case 'int64_t': | ||
case 'HostPort': | ||
return { type: 'number' }; | ||
case 'std::string': | ||
return { type: 'string' }; | ||
case 'bool': | ||
return { type: 'boolean' }; | ||
default: | ||
throw new Error( | ||
formatErrorMessage(ERRORS.missingTypeDefinition, { type }) | ||
); | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do I understand correctly that this parses the C++ source code to get the options? If so this feels like a misstep. The current C++ option parser puts an overhead at runtime to add the options. Ideally that should be refactored to add most of the options at compile time and let the parser be statically generated to eliminate the overhead and eliminate more static STL containers. Parsing the source code in an ad-hoc way in another tooling that would break the tests makes it harder to change the parser in the future, the more we do it the more the doc tooling can become a road block on performance optimisations of core which doesn't sound right. It would be better to use the binary to get the options instead of counting on the source code to be a particular shape.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks @joyeecheung for the feedback! I feel the straightforward way is to simply use the existing code incorporated on this repository? Or should the generation of the
node.config.json
schema simply not be handled by theapi-docs-tooling
🤔 any thoughts or alternatives are appreciated 🙇There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think in turns of churn/volatility, using public APIs is better than using internal APIs, and using internal APIs is better than parsing the source. It might warrant a feature request for a public API of this?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks Joyee, that feels like a good path forward.