appmesh 3.1.20 → 3.1.22

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.
@@ -8,7 +8,7 @@ import { once } from 'events'
8
8
  import { v1 as uuidv1 } from 'uuid'
9
9
  import msgpack from 'msgpack-lite'
10
10
  import AppMeshClient, {
11
- AppMeshError, AppRemovedError, TransportDisconnectedError, DEFAULT_CA_FILE, CONSTANTS,
11
+ AppMeshError, AppMeshRequestError, AppRemovedError, TransportDisconnectedError, DEFAULT_CA_FILE, CONSTANTS,
12
12
  _resolveUid, _resolveGid, _resolveUserName, _resolveGroupName,
13
13
  } from './appmesh.js'
14
14
  import { canonicalQuery } from './request_signature.js'
@@ -615,15 +615,17 @@ class AppMeshClientTCP extends AppMeshClient {
615
615
  * @override
616
616
  */
617
617
  async _request (method, path, body = null, options = {}) {
618
- // A subscribe upgrade in progress owns the read side; wait for it so this
619
- // request is routed by UUID instead of racing the new reader for frames
620
- // (the subscribe ack could otherwise resolve this request, stranding
621
- // subscribe). The wait precedes construction so signatures stay fresh.
622
- if (this._demuxerStarting) {
618
+ return this._requestOnTransport(null, method, path, body, options)
619
+ }
620
+
621
+ // Use the primary transport when ephemeralTransport is null, else bypass the demuxer.
622
+ async _requestOnTransport (ephemeralTransport, method, path, body = null, options = {}) {
623
+ const transport = ephemeralTransport || this.tcpTransport
624
+ if (!ephemeralTransport && this._demuxerStarting) {
623
625
  await this._demuxerEnablePromise
624
626
  }
625
- if (!this.tcpTransport.connected()) {
626
- await this.tcpTransport.connect()
627
+ if (!transport.connected()) {
628
+ await transport.connect()
627
629
  }
628
630
 
629
631
  // Build request message
@@ -684,13 +686,21 @@ class AppMeshClientTCP extends AppMeshClient {
684
686
  const serialized = request.serialize()
685
687
 
686
688
  let response
687
- if (this._demuxer && this._demuxer._running) {
689
+ if (ephemeralTransport) {
690
+ transport.sendMessage(serialized)
691
+ const respData = await transport.receiveMessage()
692
+ if (!respData || respData.length === 0) {
693
+ transport.close()
694
+ throw new Error('Socket connection broken')
695
+ }
696
+ response = new ResponseMessage().deserialize(respData)
697
+ } else if (this._demuxer && this._demuxer._running) {
688
698
  // Live demuxer: route response by UUID. A stopped demuxer can never resolve
689
699
  // waiters, so fall back to the direct read below. Contract S7: register the
690
700
  // waiter BEFORE writing request bytes so a fast response can't be dropped.
691
701
  const respPromise = this._demuxer.registerRequest(request.uuid)
692
702
  try {
693
- this.tcpTransport.sendMessage(serialized)
703
+ transport.sendMessage(serialized)
694
704
  } catch (e) {
695
705
  respPromise.catch(() => {}) // never dispatched; silence a later stop() rejection
696
706
  this._demuxer.unregisterRequest(request.uuid)
@@ -709,10 +719,10 @@ class AppMeshClientTCP extends AppMeshClient {
709
719
  // subscribe waits for this response before starting the demuxer.
710
720
  this._directReads++
711
721
  try {
712
- this.tcpTransport.sendMessage(serialized)
713
- const respData = await this.tcpTransport.receiveMessage()
722
+ transport.sendMessage(serialized)
723
+ const respData = await transport.receiveMessage()
714
724
  if (!respData || respData.length === 0) {
715
- this.tcpTransport.close()
725
+ transport.close()
716
726
  throw new Error('Socket connection broken')
717
727
  }
718
728
  response = new ResponseMessage().deserialize(respData)
@@ -745,7 +755,7 @@ class AppMeshClientTCP extends AppMeshClient {
745
755
  if (canRefresh && typeof provider.refreshAccessToken === 'function') {
746
756
  const newToken = await provider.refreshAccessToken(token || null)
747
757
  if (typeof newToken === 'string' && newToken.trim()) {
748
- return this._request(method, path, body, { ...options, __appmeshRetried: true })
758
+ return this._requestOnTransport(ephemeralTransport, method, path, body, { ...options, __appmeshRetried: true })
749
759
  }
750
760
  }
751
761
  }
@@ -900,77 +910,79 @@ class AppMeshClientTCP extends AppMeshClient {
900
910
  * @override
901
911
  */
902
912
  async downloadFile(filePath, localFile = null, applyAttrs = false) {
903
- this._ensureNoActiveDemuxer()
904
913
  if (!localFile) localFile = filePath.split(/[\\/]/).pop()
905
914
  const headers = {
906
915
  [HTTP_HEADER_KEY_X_FILE_PATH]: encodeURIComponent(filePath),
907
916
  [HTTP_HEADER_KEY_X_RECV_FILE_SOCKET]: 'true'
908
917
  }
909
918
 
910
- const response = await this._request(
911
- 'get',
912
- '/appmesh/file/download',
913
- null,
914
- {
915
- headers
919
+ const ephemeral = this._hasActiveDemuxer() ? this._newFileTransport() : null
920
+ const transport = ephemeral || this.tcpTransport
921
+ try {
922
+ const response = ephemeral
923
+ ? await this._requestOnTransport(ephemeral, 'get', '/appmesh/files', null, { headers })
924
+ : await this._request('get', '/appmesh/files', null, { headers })
925
+
926
+ if (!response.headers[HTTP_HEADER_KEY_X_RECV_FILE_SOCKET]) {
927
+ throw new Error(
928
+ `Server did not respond with socket transfer option: ${HTTP_HEADER_KEY_X_RECV_FILE_SOCKET}`
929
+ )
916
930
  }
917
- )
918
-
919
- if (!response.headers[HTTP_HEADER_KEY_X_RECV_FILE_SOCKET]) {
920
- throw new Error(
921
- `Server did not respond with socket transfer option: ${HTTP_HEADER_KEY_X_RECV_FILE_SOCKET}`
922
- )
923
- }
924
931
 
925
- // Receive file chunks
926
- const writeStream = fs.createWriteStream(localFile)
927
- try {
928
- while (true) {
929
- const chunk = await this.tcpTransport.receiveMessage()
930
- if (!chunk || chunk.length === 0) {
931
- break
932
- }
933
- // Honor stream backpressure so large downloads do not buffer in memory
934
- if (!writeStream.write(chunk)) {
935
- await once(writeStream, 'drain')
932
+ // Receive file chunks
933
+ const writeStream = fs.createWriteStream(localFile)
934
+ try {
935
+ while (true) {
936
+ const chunk = await transport.receiveMessage()
937
+ if (!chunk || chunk.length === 0) {
938
+ break
939
+ }
940
+ // Honor stream backpressure so large downloads do not buffer in memory
941
+ if (!writeStream.write(chunk)) {
942
+ await once(writeStream, 'drain')
943
+ }
936
944
  }
945
+ } finally {
946
+ // Await the flush so the file is complete on disk before this resolves.
947
+ await new Promise((resolve, reject) => {
948
+ writeStream.once('finish', resolve)
949
+ writeStream.once('error', reject)
950
+ writeStream.end()
951
+ })
937
952
  }
938
- } finally {
939
- // Await the flush so the file is complete on disk before this resolves.
940
- await new Promise((resolve, reject) => {
941
- writeStream.once('finish', resolve)
942
- writeStream.once('error', reject)
943
- writeStream.end()
944
- })
945
- }
946
953
 
947
- // Apply file attributes on Unix systems
948
- if (applyAttrs && process.platform !== 'win32') {
949
- // Mode is sent as a decimal string (matches the HTTP transport and Python SDK)
950
- if (response.headers[HTTP_HEADER_KEY_X_FILE_MODE]) {
951
- const mode = parseInt(response.headers[HTTP_HEADER_KEY_X_FILE_MODE], 10)
952
- // A malformed or out-of-range remote value must not fail the finished download
953
- if (Number.isInteger(mode) && mode >= 0 && mode <= 0o777) {
954
- fs.chmodSync(localFile, mode)
955
- } else {
956
- console.warn(`Warning: Invalid X-File-Mode value: ${response.headers[HTTP_HEADER_KEY_X_FILE_MODE]}`)
954
+ // Apply file attributes on Unix systems
955
+ if (applyAttrs && process.platform !== 'win32') {
956
+ // Mode is sent as a decimal string (matches the HTTP transport and Python SDK)
957
+ if (response.headers[HTTP_HEADER_KEY_X_FILE_MODE]) {
958
+ const mode = parseInt(response.headers[HTTP_HEADER_KEY_X_FILE_MODE], 10)
959
+ // A malformed or out-of-range remote value must not fail the finished download
960
+ if (Number.isInteger(mode) && mode >= 0 && mode <= 0o777) {
961
+ fs.chmodSync(localFile, mode)
962
+ } else {
963
+ console.warn(`Warning: Invalid X-File-Mode value: ${response.headers[HTTP_HEADER_KEY_X_FILE_MODE]}`)
964
+ }
957
965
  }
958
- }
959
- if (response.headers[HTTP_HEADER_KEY_X_FILE_USER] && response.headers[HTTP_HEADER_KEY_X_FILE_GROUP]) {
960
- // The daemon sends user/group *names* (os::fileStat); resolve them to
961
- // numeric uid/gid locally before chown, same as the HTTP transport.
962
- const uid = await _resolveUid(response.headers[HTTP_HEADER_KEY_X_FILE_USER])
963
- const gid = await _resolveGid(response.headers[HTTP_HEADER_KEY_X_FILE_GROUP])
964
- if (uid !== null && gid !== null) {
965
- try {
966
- fs.chownSync(localFile, uid, gid)
967
- } catch (err) {
968
- console.warn(
969
- `Warning: Unable to change owner/group of ${localFile}. Operation requires elevated privileges.`
970
- )
966
+ if (response.headers[HTTP_HEADER_KEY_X_FILE_USER] && response.headers[HTTP_HEADER_KEY_X_FILE_GROUP]) {
967
+ // The daemon sends user/group *names* (os::fileStat); resolve them to
968
+ // numeric uid/gid locally before chown, same as the HTTP transport.
969
+ const uid = await _resolveUid(response.headers[HTTP_HEADER_KEY_X_FILE_USER])
970
+ const gid = await _resolveGid(response.headers[HTTP_HEADER_KEY_X_FILE_GROUP])
971
+ if (uid !== null && gid !== null) {
972
+ try {
973
+ fs.chownSync(localFile, uid, gid)
974
+ } catch (err) {
975
+ console.warn(
976
+ `Warning: Unable to change owner/group of ${localFile}. Operation requires elevated privileges.`
977
+ )
978
+ }
971
979
  }
972
980
  }
973
981
  }
982
+ } finally {
983
+ if (ephemeral) {
984
+ ephemeral.close()
985
+ }
974
986
  }
975
987
  }
976
988
 
@@ -986,7 +998,6 @@ class AppMeshClientTCP extends AppMeshClient {
986
998
  * @override
987
999
  */
988
1000
  async uploadFile(localFile, filePath = null, applyAttrs = false, overwrite = false) {
989
- this._ensureNoActiveDemuxer()
990
1001
  if (!filePath) filePath = localFile.split(/[\\/]/).pop()
991
1002
  if (!fs.existsSync(localFile)) {
992
1003
  throw new Error(`Local file not found: ${localFile}`)
@@ -995,7 +1006,8 @@ class AppMeshClientTCP extends AppMeshClient {
995
1006
  const headers = {
996
1007
  [HTTP_HEADER_KEY_X_FILE_PATH]: encodeURIComponent(filePath),
997
1008
  'Content-Type': 'text/plain',
998
- [HTTP_HEADER_KEY_X_SEND_FILE_SOCKET]: 'true'
1009
+ [HTTP_HEADER_KEY_X_SEND_FILE_SOCKET]: 'true',
1010
+ 'X-File-Upload-Ack': 'true'
999
1011
  }
1000
1012
  if (overwrite) {
1001
1013
  headers[HTTP_HEADER_KEY_X_FILE_OVERWRITE] = 'true'
@@ -1014,27 +1026,70 @@ class AppMeshClientTCP extends AppMeshClient {
1014
1026
  headers[HTTP_HEADER_KEY_X_FILE_GROUP] = groupName || String(stats.gid)
1015
1027
  }
1016
1028
 
1017
- const response = await this._request('post', '/appmesh/file/upload', null, {
1018
- headers
1019
- })
1029
+ const ephemeral = this._hasActiveDemuxer() ? this._newFileTransport() : null
1030
+ const transport = ephemeral || this.tcpTransport
1031
+ try {
1032
+ const response = ephemeral
1033
+ ? await this._requestOnTransport(ephemeral, 'post', '/appmesh/files', null, { headers })
1034
+ : await this._request('post', '/appmesh/files', null, { headers })
1035
+
1036
+ if (!response.headers[HTTP_HEADER_KEY_X_SEND_FILE_SOCKET]) {
1037
+ throw new Error(
1038
+ `Server did not respond with socket transfer option: ${HTTP_HEADER_KEY_X_SEND_FILE_SOCKET}`
1039
+ )
1040
+ }
1020
1041
 
1021
- if (!response.headers[HTTP_HEADER_KEY_X_SEND_FILE_SOCKET]) {
1022
- throw new Error(
1023
- `Server did not respond with socket transfer option: ${HTTP_HEADER_KEY_X_SEND_FILE_SOCKET}`
1024
- )
1025
- }
1042
+ // Send file chunks
1043
+ const readStream = fs.createReadStream(localFile, {
1044
+ highWaterMark: TCP_BLOCK_SIZE
1045
+ })
1026
1046
 
1027
- // Send file chunks
1028
- const readStream = fs.createReadStream(localFile, {
1029
- highWaterMark: TCP_BLOCK_SIZE
1030
- })
1047
+ for await (const chunk of readStream) {
1048
+ transport.sendMessage(chunk)
1049
+ }
1031
1050
 
1032
- for await (const chunk of readStream) {
1033
- this.tcpTransport.sendMessage(chunk)
1034
- }
1051
+ // Send EOF signal
1052
+ transport.sendMessage([])
1035
1053
 
1036
- // Send EOF signal
1037
- this.tcpTransport.sendMessage([])
1054
+ const ackOpt = _headerValue(response.headers, 'X-File-Upload-Ack')
1055
+ if (ackOpt && String(ackOpt).toLowerCase() === 'true') {
1056
+ const ackData = await transport.receiveMessage()
1057
+ if (!ackData) {
1058
+ throw new AppMeshRequestError('Upload commit acknowledgment failed: connection closed', 502)
1059
+ }
1060
+ const ack = msgpack.decode(ackData)
1061
+ if (ack.http_status !== 200) {
1062
+ const msg = this._extractErrorMessage(ack.body)
1063
+ throw new AppMeshRequestError(`HTTP ${ack.http_status}: ${msg}`, ack.http_status)
1064
+ }
1065
+ } else {
1066
+ // Flush buffered writes on an ephemeral socket before destroy() in finally.
1067
+ const sock = ephemeral && ephemeral.socket
1068
+ if (sock && typeof sock.end === 'function' && !sock.destroyed) {
1069
+ await new Promise((resolve, reject) => {
1070
+ const cleanup = () => {
1071
+ sock.removeListener('error', onError)
1072
+ sock.removeListener('close', onDone)
1073
+ }
1074
+ const onDone = () => {
1075
+ cleanup()
1076
+ resolve()
1077
+ }
1078
+ const onError = (err) => {
1079
+ cleanup()
1080
+ reject(err)
1081
+ }
1082
+ sock.once('error', onError)
1083
+ sock.once('close', onDone)
1084
+ sock.end(onDone)
1085
+ })
1086
+ }
1087
+ }
1088
+ } finally {
1089
+ if (ephemeral) {
1090
+ ephemeral.close()
1091
+ }
1092
+ }
1038
1093
  }
1039
1094
 
1040
1095
  /**
@@ -1051,9 +1106,9 @@ class AppMeshClientTCP extends AppMeshClient {
1051
1106
  async subscribe (appName, events, callback) {
1052
1107
  await this._enableDemuxer()
1053
1108
 
1054
- let path = '/appmesh/subscribe'
1109
+ let path = '/appmesh/apps/subscribe'
1055
1110
  if (appName && appName !== '*') {
1056
- path = `/appmesh/app/${appName}/subscribe`
1111
+ path = `/appmesh/apps/${appName}/subscribe`
1057
1112
  }
1058
1113
 
1059
1114
  const params = {}
@@ -1080,7 +1135,7 @@ class AppMeshClientTCP extends AppMeshClient {
1080
1135
  */
1081
1136
  async unsubscribe (subscriptionId) {
1082
1137
  try {
1083
- await this._request('delete', '/appmesh/subscribe', null, {
1138
+ await this._request('delete', '/appmesh/apps/subscribe', null, {
1084
1139
  params: { subscription_id: subscriptionId }
1085
1140
  })
1086
1141
  } catch (error) {
@@ -1108,7 +1163,7 @@ class AppMeshClientTCP extends AppMeshClient {
1108
1163
  options.params = { subscribe_events: subscribeEvents.join(',') }
1109
1164
  }
1110
1165
 
1111
- const response = await this._request('put', `/appmesh/app/${name}`, appJson, options)
1166
+ const response = await this._request('put', `/appmesh/apps/${name}`, appJson, options)
1112
1167
  const result = response.data
1113
1168
 
1114
1169
  if (callback && result.subscription_id && this._demuxer) {
@@ -1118,17 +1173,12 @@ class AppMeshClientTCP extends AppMeshClient {
1118
1173
  return result
1119
1174
  }
1120
1175
 
1121
- /**
1122
- * Reject TCP file transfers while the event demuxer owns the read side: the
1123
- * demuxer read loop would steal the raw (non-msgpack) chunk frames and
1124
- * corrupt the transfer (mirrors the Python SDK).
1125
- * @private
1126
- */
1127
- _ensureNoActiveDemuxer () {
1128
- if (this._demuxer && this._demuxer._running) {
1129
- throw new Error('file transfer is not supported while an event subscription is active over the same TCP ' +
1130
- 'connection; use a separate client instance')
1131
- }
1176
+ _hasActiveDemuxer () {
1177
+ return Boolean((this._demuxer && this._demuxer._running) || this._demuxerStarting)
1178
+ }
1179
+
1180
+ _newFileTransport () {
1181
+ return new TCPTransport(this.tcpTransport.address, this.tcpTransport.sslConfig)
1132
1182
  }
1133
1183
 
1134
1184
  /**
@@ -10,8 +10,9 @@
10
10
  // - sortedQuery: decoded k=v pairs joined with '&', sorted by key then value, empty
11
11
  // string when there is no query (%XX-decoding only; '+' stays literal)
12
12
  // - body: lowercase hex SHA-256 of the raw body bytes; no body hashes the empty string
13
- // - streamed endpoints (/appmesh/file/download|upload|delete and the SSE output|task streams)
14
- // sign the empty-string body hash (documented exemption: the streamed content is not bound)
13
+ // - streamed endpoints (the file routes GET/POST/DELETE /appmesh/files and the
14
+ // SSE output|task streams) sign the empty-string body hash (documented
15
+ // exemption: the streamed content is not bound)
15
16
  //
16
17
  // The secret is never logged and never exposed through a getter or toString().
17
18
  // Node.js only: signing uses node:crypto (no npm dependencies).
@@ -30,12 +31,13 @@ async function nodeCrypto () {
30
31
  }
31
32
 
32
33
  /** Streamed file routes: the signature binds method/path/query/timestamp/nonce, not the bytes.
33
- * The exact daemon set (RequestHardening::canonicalFileRoute) — subpaths are not exempt. */
34
- const EMPTY_BODY_EXEMPT_PATHS = new Set(['/appmesh/file/download', '/appmesh/file/upload', '/appmesh/file/delete'])
34
+ * The exact daemon set (RequestHardening::canonicalFileRoute) — subpaths are not exempt.
35
+ * GET (download), POST (upload) and DELETE share the single /appmesh/files route. */
36
+ const EMPTY_BODY_EXEMPT_PATHS = new Set(['/appmesh/files'])
35
37
 
36
- /** SSE stream routes (/appmesh/app/{name}/output|task/stream): the daemon's SSE hardening
38
+ /** SSE stream routes (/appmesh/apps/{name}/output|task/stream): the daemon's SSE hardening
37
39
  * check ignores the request body, so these sign the empty-string hash (docs/source/Streaming.md). */
38
- const EMPTY_BODY_EXEMPT_STREAM_RE = /^\/appmesh\/app\/[^/]+\/(output|task)\/stream$/
40
+ const EMPTY_BODY_EXEMPT_STREAM_RE = /^\/appmesh\/apps\/[^/]+\/(output|task)\/stream$/
39
41
 
40
42
  /** Header names (must match HTTP_HEADER_KEY_* in src/common/Utility.h). */
41
43
  export const REQUEST_SIGNATURE_HEADERS = Object.freeze({
@@ -60,8 +62,7 @@ export function isEmptyBodyExemptPath (path) {
60
62
  * Every other path passes through unchanged.
61
63
  */
62
64
  export function canonicalSigningPath (path) {
63
- if (path === '/appmesh/file/download/ws') return '/appmesh/file/download'
64
- if (path === '/appmesh/file/upload/ws') return '/appmesh/file/upload'
65
+ if (path === '/appmesh/files/ws') return '/appmesh/files'
65
66
  return path
66
67
  }
67
68
 
@@ -104,8 +105,8 @@ export class RequestSigner {
104
105
  * @param {Object} headers - request header object (mutated)
105
106
  * @param {string} method - HTTP method exactly as sent on the wire
106
107
  * @param {string} path - request path without query, exactly as sent; the
107
- * WSS data-channel file routes ("/appmesh/file/{upload,download}/ws") are
108
- * signed under the route without the trailing "/ws" (canonicalSigningPath)
108
+ * WSS data-channel file route ("/appmesh/files/ws") is signed under the
109
+ * route without the trailing "/ws" (canonicalSigningPath)
109
110
  * @param {string} canonicalQuery - already-canonicalized query ('' when none)
110
111
  * @param {Buffer|Uint8Array|null} body - raw body bytes; null means no body;
111
112
  * ignored for the streamed file endpoints, which always sign the empty hash
package/src/worker.js CHANGED
@@ -181,7 +181,7 @@ class AppMeshWorker {
181
181
  */
182
182
  async fetchTask() {
183
183
  const { processKey, appName } = this._getRuntimeEnv()
184
- const path = `/appmesh/app/${appName}/task`
184
+ const path = `/appmesh/apps/${appName}/task`
185
185
 
186
186
  const retryDelay = 100
187
187
 
@@ -250,7 +250,7 @@ class AppMeshWorker {
250
250
  */
251
251
  async sendTaskResult(result) {
252
252
  const { processKey, appName } = this._getRuntimeEnv()
253
- const path = `/appmesh/app/${appName}/task`
253
+ const path = `/appmesh/apps/${appName}/task`
254
254
 
255
255
  let response
256
256
  try {
@@ -280,7 +280,7 @@ class AppMeshWorker {
280
280
  */
281
281
  async sendTaskPartial(partial) {
282
282
  const { processKey, appName } = this._getRuntimeEnv()
283
- const path = `/appmesh/app/${appName}/task/partial`
283
+ const path = `/appmesh/apps/${appName}/task/partial`
284
284
 
285
285
  let response
286
286
  try {