@platformatic/runtime 2.74.3 → 3.0.0-alpha.2

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
@@ -5,7 +5,7 @@
5
5
  * and run json-schema-to-typescript to regenerate this file.
6
6
  */
7
7
 
8
- export type HttpsSchemasPlatformaticDevPlatformaticRuntime2743Json = {
8
+ export type PlatformaticRuntimeConfig = {
9
9
  [k: string]: unknown;
10
10
  } & {
11
11
  $schema?: string;
package/index.d.ts CHANGED
@@ -1,29 +1,32 @@
1
- import { InjectOptions, LightMyRequestResponse } from 'fastify'
2
1
  import { FastifyError } from '@fastify/error'
3
- import { BaseLogger } from 'pino'
4
- import { RuntimeGenerator } from './lib/generator/runtime-generator'
5
- export type pltRuntimeBuildServer = {
6
- address: string
7
- port: number
8
- restart: () => Promise<void>
9
- stop: () => Promise<void>
10
- inject: (opts: InjectOptions | string) => Promise<LightMyRequestResponse>
2
+ import { Configuration, ConfigurationOptions, logFatalError, parseArgs } from '@platformatic/foundation'
3
+ import { BaseGenerator } from '@platformatic/generators'
4
+ import { JSONSchemaType } from 'ajv'
5
+ import * as colorette from 'colorette'
6
+ import { Logger } from 'pino'
7
+ import { PlatformaticRuntimeConfig } from './config'
8
+
9
+ export type RuntimeConfiguration = Promise<Configuration<PlatformaticRuntimeConfig>>
10
+
11
+ export type ServiceCommandContext = {
12
+ colorette: typeof colorette
13
+ parseArgs: typeof parseArgs
14
+ logFatalError: typeof logFatalError
11
15
  }
12
16
 
13
- declare module '@platformatic/runtime' {
14
- export function buildServer (opts: object): Promise<pltRuntimeBuildServer>
15
- export function start (args: object): Promise<object>
16
- export function startCommand (args: object): Promise<void>
17
- export function loadConfig (minimistConfig: object, args: object, store: object, overrides: object, replaceEnv: boolean): void
18
- export function compile (argv: string[], logger: BaseLogger): void
19
- export function platformaticRuntime (): Promise<void>
20
- export function wrapConfigInRuntimeConfig (args: object): object
21
- export const Generator: RuntimeGenerator.RuntimeGenerator
17
+ export type ServiceCommand = (
18
+ logger: Logger,
19
+ configuration: Configuration<unknown>,
20
+ args: string[],
21
+ context: ServiceCommandContext
22
+ ) => Promise<void>
23
+
24
+ export interface ServicesCommands {
25
+ services: Record<string, Configuration<unknown>>
26
+ commands: Record<string, ServiceCommand>
27
+ help: Record<string, string | (() => string)>
22
28
  }
23
29
 
24
- /**
25
- * All the errors thrown by the plugin.
26
- */
27
30
  export module errors {
28
31
  export const RuntimeExitedError: () => FastifyError
29
32
  export const UnknownRuntimeAPICommandError: (command: string) => FastifyError
@@ -43,3 +46,49 @@ export module errors {
43
46
  export const CannotMapSpecifierToAbsolutePathError: (specifier: string) => FastifyError
44
47
  export const NodeInspectorFlagsNotSupportedError: () => FastifyError
45
48
  }
49
+
50
+ export module symbols {
51
+ export declare const kConfig: unique symbol
52
+ export declare const kId: unique symbol
53
+ export declare const kFullId: unique symbol
54
+ export declare const kServiceId: unique symbol
55
+ export declare const kWorkerId: unique symbol
56
+ export declare const kITC: unique symbol
57
+ export declare const kHealthCheckTimer: unique symbol
58
+ export declare const kLastELU: unique symbol
59
+ export declare const kWorkerStatus: unique symbol
60
+ export declare const kStderrMarker: string
61
+ export declare const kInterceptors: unique symbol
62
+ export declare const kWorkersBroadcast: unique symbol
63
+ }
64
+
65
+ export class Generator extends BaseGenerator.BaseGenerator {}
66
+
67
+ export class WrappedGenerator extends BaseGenerator.BaseGenerator {}
68
+
69
+ export declare const schema: JSONSchemaType<PlatformaticRuntimeConfig>
70
+
71
+ export declare class Runtime {}
72
+
73
+ export function wrapInRuntimeConfig (
74
+ config: Configuration<unknown>,
75
+ context?: ConfigurationOptions
76
+ ): Promise<RuntimeConfiguration>
77
+
78
+ export declare const version: string
79
+
80
+ export declare function loadConfiguration (
81
+ root: string | PlatformaticRuntimeConfig,
82
+ source?: string | PlatformaticRuntimeConfig,
83
+ context?: ConfigurationOptions
84
+ ): Promise<RuntimeConfiguration>
85
+
86
+ export function create (
87
+ root: string,
88
+ source?: string | PlatformaticRuntimeConfig,
89
+ context?: ConfigurationOptions
90
+ ): Promise<Runtime>
91
+
92
+ export declare function transform (config: RuntimeConfiguration): Promise<RuntimeConfiguration> | RuntimeConfiguration
93
+
94
+ export declare function loadServicesCommands (): Promise<ServicesCommands>
package/index.js CHANGED
@@ -1,30 +1,163 @@
1
1
  'use strict'
2
2
 
3
- const { buildServer } = require('./lib/build-server')
4
- const { compile } = require('./lib/compile')
5
- const errors = require('./lib/errors')
6
- const { platformaticRuntime, wrapConfigInRuntimeConfig } = require('./lib/config')
7
- const { RuntimeGenerator, WrappedGenerator } = require('./lib/generator/runtime-generator')
3
+ const inspector = require('node:inspector')
4
+ const {
5
+ kMetadata,
6
+ loadConfigurationModule,
7
+ abstractLogger,
8
+ findRuntimeConfigurationFile,
9
+ loadConfiguration: utilsLoadConfiguration,
10
+ extractModuleFromSchemaUrl,
11
+ ensureLoggableError
12
+ } = require('@platformatic/foundation')
13
+ const { resolve, validationOptions } = require('@platformatic/basic')
14
+ const { NodeInspectorFlagsNotSupportedError } = require('./lib/errors')
15
+ const { wrapInRuntimeConfig, transform } = require('./lib/config')
16
+ const { RuntimeGenerator, WrappedGenerator } = require('./lib/generator')
8
17
  const { Runtime } = require('./lib/runtime')
9
- const { buildRuntime, start, startCommand } = require('./lib/start')
10
18
  const symbols = require('./lib/worker/symbols')
11
- const { loadConfig, getRuntimeLogsDir } = require('./lib/utils')
19
+ const { schema } = require('./lib/schema')
20
+ const { upgrade } = require('./lib/upgrade')
21
+
22
+ async function restartRuntime (runtime) {
23
+ runtime.logger.info('Received SIGUSR2, restarting all services ...')
24
+
25
+ try {
26
+ await runtime.restart()
27
+ } catch (err) {
28
+ runtime.logger.error({ err: ensureLoggableError(err) }, 'Failed to restart services.')
29
+ }
30
+ }
31
+
32
+ function handleSignal (runtime) {
33
+ /* c8 ignore next 3 */
34
+ const restartListener = restartRuntime.bind(null, runtime)
35
+ process.on('SIGUSR2', restartListener)
36
+ runtime.on('closed', () => {
37
+ process.removeListener('SIGUSR2', restartListener)
38
+ })
39
+ }
40
+
41
+ async function loadConfiguration (configOrRoot, sourceOrConfig, context) {
42
+ const { root, source } = await resolve(configOrRoot, sourceOrConfig, 'runtime')
43
+
44
+ // First of all, load the configuration without any validation
45
+ const config = await utilsLoadConfiguration(source)
46
+ const mod = extractModuleFromSchemaUrl(config)
47
+ if (mod?.module !== '@platformatic/runtime') {
48
+ return wrapInRuntimeConfig(config, context)
49
+ }
50
+
51
+ return utilsLoadConfiguration(source, context?.schema ?? schema, {
52
+ validationOptions,
53
+ transform,
54
+ upgrade,
55
+ replaceEnv: true,
56
+ root,
57
+ ...context
58
+ })
59
+ }
60
+
61
+ async function loadServicesCommands () {
62
+ const services = {}
63
+ const commands = {}
64
+ const help = {}
65
+
66
+ let config
67
+ try {
68
+ const file = await findRuntimeConfigurationFile(abstractLogger, process.cwd(), null, false, false)
69
+
70
+ /* c8 ignore next 3 - Hard to test */
71
+ if (!file) {
72
+ throw new Error('No runtime configuration file found.')
73
+ }
74
+
75
+ config = await loadConfiguration(file)
76
+
77
+ /* c8 ignore next 3 - Hard to test */
78
+ if (!config) {
79
+ throw new Error('No runtime configuration file found.')
80
+ }
81
+ } catch {
82
+ return { services, commands, help }
83
+ }
84
+
85
+ for (const service of config.services) {
86
+ try {
87
+ const serviceConfig = await utilsLoadConfiguration(service.config)
88
+ const pkg = await loadConfigurationModule(service.path, serviceConfig)
89
+
90
+ if (pkg.createCommands) {
91
+ const definition = await pkg.createCommands(service.id)
92
+ for (const command of Object.keys(definition.commands)) {
93
+ services[command] = service
94
+ }
95
+
96
+ Object.assign(commands, definition.commands)
97
+ Object.assign(help, definition.help)
98
+ }
99
+ /* c8 ignore next 3 - Hard to test */
100
+ } catch {
101
+ // No-op, ignore the service
102
+ }
103
+ }
104
+
105
+ return { services, commands, help }
106
+ }
107
+
108
+ async function create (configOrRoot, sourceOrConfig, context) {
109
+ const config = await loadConfiguration(configOrRoot, sourceOrConfig, context)
110
+
111
+ if (inspector.url() && !config[kMetadata].env.VSCODE_INSPECTOR_OPTIONS) {
112
+ throw new NodeInspectorFlagsNotSupportedError()
113
+ }
114
+
115
+ let runtime = new Runtime(config, context)
116
+ handleSignal(runtime)
117
+
118
+ // Handle port handling
119
+ if (context?.start) {
120
+ let port = config.server?.port
121
+
122
+ while (true) {
123
+ try {
124
+ await runtime.start()
125
+ break
126
+ } catch (err) {
127
+ if ((err.code !== 'EADDRINUSE' && err.code !== 'EACCES') || context?.skipPortInUseHandling) {
128
+ throw err
129
+ }
130
+
131
+ await runtime.close()
132
+
133
+ // Get the actual port from the error message if original port was 0
134
+ if (!port) {
135
+ const mo = err.message.match(/ address already in use (.+)/)
136
+ const url = new URL(`http://${mo[1]}`)
137
+ port = Number(url.port)
138
+ }
139
+
140
+ config.server.port = ++port
141
+ runtime = new Runtime(config, context)
142
+ handleSignal(runtime)
143
+ }
144
+ }
145
+ }
146
+
147
+ return runtime
148
+ }
12
149
 
13
150
  const platformaticVersion = require('./package.json').version
14
151
 
15
- module.exports.buildServer = buildServer
16
- module.exports.buildRuntime = buildRuntime
17
- module.exports.compile = compile
18
- module.exports.errors = errors
152
+ module.exports.errors = require('./lib/errors')
19
153
  module.exports.Generator = RuntimeGenerator
20
154
  module.exports.WrappedGenerator = WrappedGenerator
21
- module.exports.getRuntimeLogsDir = getRuntimeLogsDir
22
- module.exports.loadConfig = loadConfig
23
- module.exports.platformaticRuntime = platformaticRuntime
24
- module.exports.schema = platformaticRuntime.schema
25
- module.exports.start = start
26
- module.exports.startCommand = startCommand
155
+ module.exports.schema = schema
27
156
  module.exports.symbols = symbols
28
157
  module.exports.Runtime = Runtime
29
- module.exports.wrapConfigInRuntimeConfig = wrapConfigInRuntimeConfig
158
+ module.exports.wrapInRuntimeConfig = wrapInRuntimeConfig
30
159
  module.exports.version = platformaticVersion
160
+ module.exports.loadConfiguration = loadConfiguration
161
+ module.exports.create = create
162
+ module.exports.transform = transform
163
+ module.exports.loadServicesCommands = loadServicesCommands