@yamf/services-pm3 0.1.0 → 0.9.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.
Files changed (3) hide show
  1. package/LICENSE +21 -0
  2. package/package.json +10 -6
  3. package/service.js +98 -9
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2017 mcbrumagin
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/package.json CHANGED
@@ -1,8 +1,11 @@
1
1
  {
2
2
  "name": "@yamf/services-pm3",
3
- "version": "0.1.0",
3
+ "version": "0.9.0",
4
4
  "description": "PM3 process management service for yamf - enables remote CLI capabilities",
5
- "license": "ISC",
5
+ "license": "MIT",
6
+ "engines": {
7
+ "node": ">=22.0.0"
8
+ },
6
9
  "author": "",
7
10
  "type": "module",
8
11
  "main": "service.js",
@@ -11,13 +14,14 @@
11
14
  ],
12
15
  "dependencies": {},
13
16
  "peerDependencies": {
14
- "@yamf/core": "0.4.0",
15
- "@yamf/cli": "0.2.0"
17
+ "@yamf/core": "0.9.0",
18
+ "@yamf/cli": "0.9.0"
16
19
  },
17
20
  "devDependencies": {
18
- "@yamf/test": "0.1.4"
21
+ "@yamf/test": "0.9.0"
19
22
  },
20
23
  "scripts": {
21
- "test": "yamf test -d ."
24
+ "test": "yamf test -d .",
25
+ "test:all": "yamf test -d . --include-e2e"
22
26
  }
23
27
  }
package/service.js CHANGED
@@ -1,12 +1,65 @@
1
1
  import {
2
2
  createService,
3
3
  Logger,
4
- HttpError
4
+ HttpError,
5
+ envConfig,
6
+ HEADERS
5
7
  } from '@yamf/core'
8
+ import { createWriteStream, existsSync, mkdirSync, renameSync } from 'node:fs'
9
+ import { join } from 'node:path'
10
+ import { pipeline } from 'node:stream/promises'
11
+ import { Readable } from 'node:stream'
6
12
 
7
13
  import { PM3 } from '@yamf/cli'
8
14
 
9
- const logger = new Logger({ logGroup: 'pm3-service' })
15
+ const logger = new Logger({ logGroup: 'pm3' })
16
+
17
+ /**
18
+ * When YAMF_DEPLOY_TOKEN is set, deploy and rolling-deploy require the same value in
19
+ * the proxied yamf-deploy-token header (enforced for SERVICE_CALL, not just registry plugin commands).
20
+ * @param {import('node:http').IncomingMessage | undefined} request
21
+ */
22
+ function assertDeployTokenForCommand (request) {
23
+ const expected = envConfig.get('YAMF_DEPLOY_TOKEN', '')
24
+ if (!expected) {
25
+ return
26
+ }
27
+ const v = (request) => {
28
+ const h = request?.headers || {}
29
+ return h[HEADERS.DEPLOY_TOKEN] || h['yamf-deploy-token']
30
+ }
31
+ if (v(request) !== expected) {
32
+ throw new HttpError(401, 'Invalid or missing deploy token for this command')
33
+ }
34
+ }
35
+
36
+ /**
37
+ * @param {string} managedServicePath
38
+ * @param {string} hash
39
+ * @returns {Promise<string>} absolute bundle path
40
+ */
41
+ async function ensureBundleFile (managedServicePath, hash) {
42
+ const bundlePath = join(managedServicePath, `${hash}.mjs`)
43
+ if (existsSync(bundlePath)) {
44
+ return bundlePath
45
+ }
46
+ const registryUrl = envConfig.get('YAMF_REGISTRY_URL', '')
47
+ if (!registryUrl) {
48
+ throw new HttpError(500, 'YAMF_REGISTRY_URL required to fetch bundle')
49
+ }
50
+ const base = registryUrl.replace(/\/$/, '')
51
+ const u = new URL(`${base}/bundles/${String(hash).replace(/\.mjs$/, '')}`)
52
+ const token = envConfig.get('YAMF_DEPLOY_TOKEN', '')
53
+ const res = await fetch(u, { headers: { ...(token ? { 'yamf-deploy-token': token } : {}) } })
54
+ if (!res.ok) {
55
+ throw new HttpError(502, `bundle fetch failed: ${res.status}`)
56
+ }
57
+ mkdirSync(managedServicePath, { recursive: true })
58
+ const tmp = bundlePath + '.part'
59
+ await pipeline(Readable.fromWeb(res.body), createWriteStream(tmp))
60
+ renameSync(tmp, bundlePath)
61
+ return bundlePath
62
+ }
10
63
 
11
64
  /**
12
65
  * PM3 Service - network-facing process manager for yamf nodes.
@@ -16,17 +69,17 @@ const logger = new Logger({ logGroup: 'pm3-service' })
16
69
  *
17
70
  * For now, this service is NOT recommended for production use.
18
71
  */
19
- export default async function createPm3Service({
20
- serviceName = 'pm3-service',
72
+ export default async function createPm3Service ({
73
+ serviceName = 'pm3',
21
74
  managedServicePath = '/tmp/yamf/services'
22
75
  } = {}) {
23
76
  const pm3 = new PM3()
24
77
 
25
- const service = await createService(serviceName, async function (payload) {
78
+ const service = await createService(serviceName, async function (payload, request) {
26
79
  const { command, filepath, options } = payload || {}
27
80
 
28
81
  if (!command) {
29
- throw new HttpError(400, 'command is required (start, stop, restart, list, status, logs, delete)')
82
+ throw new HttpError(400, 'command is required (start, stop, restart, restart-rolling, list, status, logs, delete, deploy, rolling-deploy)')
30
83
  }
31
84
 
32
85
  switch (command) {
@@ -42,6 +95,13 @@ export default async function createPm3Service({
42
95
  if (!filepath) throw new HttpError(400, 'filepath is required for restart')
43
96
  return pm3.restart(filepath, options)
44
97
  }
98
+ case 'restart-rolling': {
99
+ const { target, options: rollOpts } = payload || {}
100
+ if (!target) {
101
+ throw new HttpError(400, 'target is required for restart-rolling (service name or filepath on this node)')
102
+ }
103
+ return pm3.restartRolling(target, rollOpts || {})
104
+ }
45
105
  case 'list': {
46
106
  return pm3.list(options)
47
107
  }
@@ -51,15 +111,44 @@ export default async function createPm3Service({
51
111
  }
52
112
  case 'logs': {
53
113
  if (!filepath) throw new HttpError(400, 'filepath is required for logs')
54
- return pm3.logs(filepath)
114
+ return pm3.logs(filepath, options || {})
55
115
  }
56
116
  case 'delete': {
57
117
  if (!filepath) throw new HttpError(400, 'filepath is required for delete')
58
118
  return pm3.delete(filepath)
59
119
  }
60
- // future: 'deploy' command for receiving esbuild bundles
120
+ case 'deploy': {
121
+ assertDeployTokenForCommand(request)
122
+ const { service, hash, env: spawnEnv = {} } = payload || {}
123
+ if (!hash) {
124
+ throw new HttpError(400, 'hash is required (YAMF_SOURCE_HASH from deploy)')
125
+ }
126
+ const bundlePath = await ensureBundleFile(managedServicePath, hash)
127
+ const nodeId = process.env.YAMF_SERVICE_URL || null
128
+ return pm3.start(bundlePath, {
129
+ env: {
130
+ ...spawnEnv,
131
+ YAMF_SOURCE_HASH: hash,
132
+ YAMF_BUNDLE_PATH: bundlePath,
133
+ ...(service ? { YAMF_SERVICE_NAME: service } : {}),
134
+ ...(nodeId ? { YAMF_NODE_ID: nodeId } : {})
135
+ }
136
+ })
137
+ }
138
+ case 'rolling-deploy': {
139
+ assertDeployTokenForCommand(request)
140
+ const { service, hash, env } = payload || {}
141
+ if (!service) {
142
+ throw new HttpError(400, 'service is required for rolling-deploy')
143
+ }
144
+ if (!hash) {
145
+ throw new HttpError(400, 'hash is required for rolling-deploy')
146
+ }
147
+ const bundlePath = await ensureBundleFile(managedServicePath, hash)
148
+ return pm3.restartRolling(service, { env, bundlePath })
149
+ }
61
150
  default:
62
- throw new HttpError(400, `Unknown command: ${command}. Valid: start, stop, restart, list, status, logs, delete`)
151
+ throw new HttpError(400, `Unknown command: ${command}. Valid: start, stop, restart, restart-rolling, list, status, logs, delete, deploy, rolling-deploy`)
63
152
  }
64
153
  })
65
154