langmart-gateway-type3 3.0.9 → 3.0.11

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/scripts/start.ps1 CHANGED
@@ -1,142 +1,144 @@
1
- # Start Gateway Type 3 on Windows
2
- # This script is designed to work both interactively and via SSH
1
+ # Gateway Type 3 Start Script for Windows
2
+ # Features: Service mode detection, pre-flight checks, RESULT output
3
3
 
4
- param(
5
- [int]$Port = 8083,
6
- [string]$MarketplaceUrl = "",
7
- [string]$ApiKey = "",
8
- [switch]$Quiet
9
- )
4
+ param([int]$Port = 0, [string]$MarketplaceUrl = "", [string]$ApiKey = "", [string]$GatewayId = "")
10
5
 
11
- # Get script directory (works whether run from npm or directly)
12
6
  $ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
13
7
  $ProjectDir = Split-Path -Parent $ScriptDir
8
+ $InstallDir = if ($ProjectDir -like "*node_modules*") { (Get-Location).Path } else { $ProjectDir }
14
9
 
15
- # If running from node_modules, adjust path
16
- if ($ProjectDir -like "*node_modules*") {
17
- $ProjectDir = (Get-Location).Path
18
- if (Test-Path "$ProjectDir\node_modules\langmart-gateway-type3") {
19
- $EntryFile = "$ProjectDir\node_modules\langmart-gateway-type3\dist\index-server.js"
20
- } else {
21
- $EntryFile = "$ProjectDir\dist\index-server.js"
10
+ $EnvFile = Join-Path $InstallDir ".env"
11
+ $LogDir = Join-Path $InstallDir "logs"
12
+ $LogFile = Join-Path $LogDir "gateway.log"
13
+ $PidFile = Join-Path $InstallDir "gateway.pid"
14
+ $ServiceModeFile = Join-Path $InstallDir ".service-mode"
15
+ $ServiceName = "LangMartGateway"
16
+
17
+ function Write-Log { param([string]$Message, [string]$Type = "INFO"); Write-Output "[$Type] $(Get-Date -Format 'HH:mm:ss') - $Message" }
18
+
19
+ function Load-EnvFile {
20
+ if (Test-Path $EnvFile) {
21
+ Write-Log "Loading environment from $EnvFile"
22
+ Get-Content $EnvFile | ForEach-Object {
23
+ if ($_ -match '^([^#=]+)=(.*)$') {
24
+ [Environment]::SetEnvironmentVariable($matches[1].Trim(), $matches[2].Trim().Trim('"').Trim("'"), 'Process')
25
+ }
26
+ }
22
27
  }
23
- } else {
24
- $EntryFile = "$ProjectDir\dist\index-server.js"
25
- }
26
-
27
- # Output helper
28
- function Write-Log {
29
- param([string]$Message, [string]$Type = "INFO")
30
- Write-Output "[$Type] $Message"
31
28
  }
32
29
 
33
- # Load .env file if exists
34
- $EnvFile = Join-Path $ProjectDir ".env"
35
- if (Test-Path $EnvFile) {
36
- Get-Content $EnvFile | ForEach-Object {
37
- if ($_ -match '^([^#][^=]+)=(.*)$') {
38
- $key = $matches[1].Trim()
39
- $value = $matches[2].Trim()
40
- [Environment]::SetEnvironmentVariable($key, $value, 'Process')
30
+ function Test-ServiceMode {
31
+ if (Test-Path $ServiceModeFile) {
32
+ $mode = Get-Content $ServiceModeFile -ErrorAction SilentlyContinue
33
+ if ($mode -eq "windows-service") {
34
+ if (Get-Service -Name $ServiceName -ErrorAction SilentlyContinue) { return $true }
41
35
  }
42
36
  }
37
+ return $false
38
+ }
39
+
40
+ function Find-EntryFile {
41
+ $npmPath = Join-Path $InstallDir "node_modules\langmart-gateway-type3\dist\index-server.js"
42
+ $devPath = Join-Path $ProjectDir "dist\index-server.js"
43
+ if (Test-Path $npmPath) { return $npmPath }
44
+ if (Test-Path $devPath) { return $devPath }
45
+ return $null
43
46
  }
44
47
 
45
- # Set configuration from parameters, environment, or defaults
46
- $GatewayPort = if ($Port -ne 8083) { $Port } elseif ($env:GATEWAY_PORT) { $env:GATEWAY_PORT } else { 8083 }
48
+ Write-Log "=== Gateway Type 3 Start Script ==="
49
+ Write-Log "Install directory: $InstallDir"
50
+ Load-EnvFile
51
+
52
+ $GatewayPort = if ($Port -gt 0) { $Port } elseif ($env:GATEWAY_PORT) { [int]$env:GATEWAY_PORT } else { 8083 }
47
53
  $GatewayApiKey = if ($ApiKey) { $ApiKey } elseif ($env:GATEWAY_API_KEY) { $env:GATEWAY_API_KEY } else { "" }
48
54
  $GatewayMarketplace = if ($MarketplaceUrl) { $MarketplaceUrl } elseif ($env:MARKETPLACE_URL) { $env:MARKETPLACE_URL } else { "ws://localhost:8081" }
55
+ $GatewayIdValue = if ($GatewayId) { $GatewayId } elseif ($env:GATEWAY_ID) { $env:GATEWAY_ID } else { "" }
56
+
57
+ # CHECK SERVICE MODE
58
+ $serviceMode = Test-ServiceMode
59
+ if ($serviceMode) {
60
+ Write-Log "Service mode detected (Windows Service)"
61
+ $service = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
62
+ if ($service.Status -eq "Running") {
63
+ try {
64
+ $existingPID = (Get-NetTCPConnection -LocalPort $GatewayPort -State Listen -ErrorAction SilentlyContinue).OwningProcess | Select-Object -First 1
65
+ if ($existingPID) {
66
+ Write-Log "Service already running (PID: $existingPID)" "SUCCESS"
67
+ Write-Output "RESULT:running=true,port=$GatewayPort,pid=$existingPID,mode=service"; exit 0
68
+ }
69
+ } catch {}
70
+ }
71
+ Write-Log "Starting via Windows Service..."
72
+ try {
73
+ Start-Service -Name $ServiceName -ErrorAction Stop; Start-Sleep -Seconds 3
74
+ $existingPID = (Get-NetTCPConnection -LocalPort $GatewayPort -State Listen -ErrorAction SilentlyContinue).OwningProcess | Select-Object -First 1
75
+ if ($existingPID) {
76
+ Write-Log "Service started successfully (PID: $existingPID)" "SUCCESS"
77
+ Write-Output "RESULT:running=true,port=$GatewayPort,pid=$existingPID,mode=service"; exit 0
78
+ }
79
+ Write-Log "Service started but gateway not listening" "ERROR"
80
+ Write-Output "RESULT:running=false,port=,pid=,mode=service"; exit 1
81
+ } catch {
82
+ Write-Log "Failed to start service: $_" "ERROR"
83
+ Write-Output "RESULT:running=false,port=,pid=,mode=service"; exit 1
84
+ }
85
+ }
49
86
 
50
- # Check for API key
51
- if (-not $GatewayApiKey) {
52
- Write-Log "GATEWAY_API_KEY not configured" "ERROR"
53
- Write-Log "Set it in .env file or pass via -ApiKey parameter" "ERROR"
54
- exit 1
87
+ # STANDALONE MODE
88
+ Write-Log "Running in standalone mode"
89
+ Write-Log "Checking required parameters..."
90
+ $missingVars = @(); if (-not $GatewayApiKey) { $missingVars += "GATEWAY_API_KEY" }; if (-not $GatewayMarketplace) { $missingVars += "MARKETPLACE_URL" }
91
+ if ($missingVars.Count -gt 0) {
92
+ Write-Log "Missing required parameters: $($missingVars -join ', ')" "ERROR"
93
+ Write-Output "RESULT:running=false,port=,pid=,mode=standalone"; exit 1
55
94
  }
56
95
 
57
- # Check if already running
96
+ Write-Log "GATEWAY_PORT: $GatewayPort"
97
+ Write-Log "MARKETPLACE_URL: $GatewayMarketplace"
98
+ Write-Log "GATEWAY_API_KEY: $($GatewayApiKey.Substring(0, [Math]::Min(8, $GatewayApiKey.Length)))..."
99
+
58
100
  try {
59
101
  $existingPID = (Get-NetTCPConnection -LocalPort $GatewayPort -State Listen -ErrorAction SilentlyContinue).OwningProcess | Select-Object -First 1
60
102
  if ($existingPID) {
61
- Write-Log "Gateway already running on port $GatewayPort (PID: $existingPID)" "WARN"
62
- exit 0
103
+ Write-Log "Gateway already running on port $GatewayPort (PID: $existingPID)" "SUCCESS"
104
+ Write-Output "RESULT:running=true,port=$GatewayPort,pid=$existingPID,mode=standalone"; exit 0
63
105
  }
64
- } catch {
65
- # Port check failed, continue with start
66
- }
106
+ } catch {}
107
+ Write-Log "Port $GatewayPort is available" "SUCCESS"
67
108
 
68
- # Check if entry file exists
69
- if (-not (Test-Path $EntryFile)) {
70
- Write-Log "Entry file not found: $EntryFile" "ERROR"
71
- exit 1
72
- }
73
-
74
- Write-Log "Starting Gateway Type 3 on Windows..."
75
- Write-Log "Port: $GatewayPort"
76
- Write-Log "Marketplace: $GatewayMarketplace"
77
- Write-Log "API Key: $($GatewayApiKey.Substring(0, [Math]::Min(10, $GatewayApiKey.Length)))..."
109
+ $EntryFile = Find-EntryFile
110
+ if (-not $EntryFile) { Write-Log "Entry file not found!" "ERROR"; Write-Output "RESULT:running=false,port=,pid=,mode=standalone"; exit 1 }
111
+ Write-Log "Entry file: $EntryFile"
78
112
 
79
- # Set environment for the gateway process
80
- $env:GATEWAY_PORT = $GatewayPort
81
- $env:MARKETPLACE_URL = $GatewayMarketplace
82
- $env:GATEWAY_API_KEY = $GatewayApiKey
113
+ Write-Log "=== Starting Gateway ==="
114
+ if (-not (Test-Path $LogDir)) { New-Item -ItemType Directory -Path $LogDir -Force | Out-Null }
115
+ if (Test-Path $LogFile) { Clear-Content $LogFile -ErrorAction SilentlyContinue }
116
+ $env:GATEWAY_PORT = $GatewayPort; $env:MARKETPLACE_URL = $GatewayMarketplace; $env:GATEWAY_API_KEY = $GatewayApiKey; $env:GATEWAY_ID = $GatewayIdValue
83
117
 
84
- # Create log directory
85
- $LogDir = Join-Path $ProjectDir "logs"
86
- if (-not (Test-Path $LogDir)) {
87
- New-Item -ItemType Directory -Path $LogDir -Force | Out-Null
88
- }
89
- $LogFile = Join-Path $LogDir "gateway.log"
90
- $ErrorLogFile = Join-Path $LogDir "gateway-error.log"
91
-
92
- # Start gateway process in background
118
+ Write-Log "Starting with: node $EntryFile"
93
119
  try {
94
- $process = Start-Process -FilePath "node" -ArgumentList $EntryFile `
95
- -WindowStyle Hidden `
96
- -PassThru `
97
- -WorkingDirectory $ProjectDir `
98
- -RedirectStandardOutput $LogFile `
99
- -RedirectStandardError $ErrorLogFile
100
-
101
- Write-Log "Process started with PID $($process.Id)"
102
-
103
- # Save PID to file
104
- $PidFile = Join-Path $ProjectDir "gateway.pid"
120
+ $ErrorLogFile = Join-Path $LogDir "gateway-error.log"
121
+ $process = Start-Process -FilePath "node" -ArgumentList $EntryFile -WindowStyle Hidden -PassThru -WorkingDirectory $InstallDir -RedirectStandardOutput $LogFile -RedirectStandardError $ErrorLogFile
105
122
  $process.Id | Out-File -FilePath $PidFile -Encoding ASCII
123
+ Write-Log "Process started with PID: $($process.Id)"
124
+ } catch { Write-Log "Failed to start gateway: $_" "ERROR"; Write-Output "RESULT:running=false,port=,pid=,mode=standalone"; exit 1 }
106
125
 
107
- } catch {
108
- Write-Log "Failed to start gateway: $_" "ERROR"
109
- exit 1
110
- }
111
-
112
- # Wait for gateway to start
113
- Write-Log "Waiting for gateway to start..."
114
- Start-Sleep -Seconds 3
115
-
116
- # Check if running
117
- $retries = 0
118
- $maxRetries = 10
119
- while ($retries -lt $maxRetries) {
126
+ Write-Log "Waiting for gateway to start listening..."
127
+ $maxWait = 15; $waitInterval = 2; $totalWaited = 0; $listening = $false; $finalPid = ""
128
+ while ($totalWaited -lt $maxWait) {
129
+ Start-Sleep -Seconds $waitInterval; $totalWaited += $waitInterval
120
130
  try {
121
- $newPID = (Get-NetTCPConnection -LocalPort $GatewayPort -State Listen -ErrorAction SilentlyContinue).OwningProcess | Select-Object -First 1
122
- if ($newPID) {
123
- Write-Log "Gateway started successfully (PID: $newPID) on port $GatewayPort" "SUCCESS"
124
- Write-Log "Logs: $LogFile"
125
- exit 0
126
- }
131
+ $checkPid = (Get-NetTCPConnection -LocalPort $GatewayPort -State Listen -ErrorAction SilentlyContinue).OwningProcess | Select-Object -First 1
132
+ if ($checkPid) { $listening = $true; $finalPid = $checkPid; break }
127
133
  } catch {}
128
- Start-Sleep -Seconds 1
129
- $retries++
134
+ Write-Log "Waiting... ($totalWaited/$maxWait seconds)"
130
135
  }
131
136
 
132
- # Check error log if failed
133
- if (Test-Path $ErrorLogFile) {
134
- $errors = Get-Content $ErrorLogFile -Tail 5 -ErrorAction SilentlyContinue
135
- if ($errors) {
136
- Write-Log "Gateway failed to start. Error log:" "ERROR"
137
- $errors | ForEach-Object { Write-Log $_ "ERROR" }
138
- }
137
+ if ($listening) {
138
+ Write-Log "Gateway confirmed listening on port $GatewayPort (PID: $finalPid)" "SUCCESS"
139
+ if (Test-Path $LogFile) { Write-Log "=== Recent log output ==="; Get-Content $LogFile -Tail 5 -ErrorAction SilentlyContinue | ForEach-Object { Write-Output $_ } }
140
+ Write-Output "RESULT:running=true,port=$GatewayPort,pid=$finalPid,mode=standalone"; exit 0
141
+ } else {
142
+ Write-Log "Gateway failed to start" "ERROR"
143
+ Write-Output "RESULT:running=false,port=,pid=,mode=standalone"; exit 1
139
144
  }
140
-
141
- Write-Log "Gateway failed to start within timeout" "ERROR"
142
- exit 1
package/scripts/start.sh CHANGED
@@ -1,85 +1,254 @@
1
1
  #!/bin/bash
2
- # Start Gateway Type 3 in background with SSH disconnect protection
3
-
4
- # Colors
5
- GREEN='\033[0;32m'
6
- YELLOW='\033[1;33m'
7
- RED='\033[0;31m'
8
- BLUE='\033[0;34m'
9
- CYAN='\033[0;36m'
10
- NC='\033[0m' # No Color
11
-
12
- # Configuration
13
- GATEWAY_PORT=8083
14
- LOG_FILE="/tmp/gw3.log"
15
- PID_FILE="/tmp/gw3.pid"
2
+ # Gateway Type 3 Start Script
3
+ # Designed to work from installed location (via npm install) or development
4
+ #
5
+ # Features:
6
+ # - Detect service mode vs standalone mode
7
+ # - Load configuration from .env file
8
+ # - Pre-flight checks (port, required params)
9
+ # - Use isolated Node.js if available (for older systems)
10
+ # - Output machine-readable RESULT line for automation
11
+
12
+ set -e
13
+
14
+ # Get script directory and project directory
16
15
  SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
17
16
  PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
18
17
 
19
- # Detect host IP
20
- HOST_IP=$(hostname -I | awk '{print $1}')
21
- if [ -z "$HOST_IP" ]; then
22
- HOST_IP="localhost"
18
+ # If running from node_modules, find the actual install dir
19
+ if [[ "$PROJECT_DIR" == *"node_modules"* ]]; then
20
+ INSTALL_DIR="$(cd "$PROJECT_DIR/../.." && pwd)"
21
+ else
22
+ INSTALL_DIR="$PROJECT_DIR"
23
23
  fi
24
24
 
25
- # Check if already running
26
- if lsof -i :$GATEWAY_PORT -sTCP:LISTEN -t >/dev/null 2>&1; then
27
- echo -e "${YELLOW}Gateway Type 3 is already running on port $GATEWAY_PORT${NC}"
28
- exit 0
25
+ # Configuration with defaults
26
+ LOG_DIR="${INSTALL_DIR}/logs"
27
+ LOG_FILE="${LOG_DIR}/gateway.log"
28
+ PID_FILE="${INSTALL_DIR}/gateway.pid"
29
+ ENV_FILE="${INSTALL_DIR}/.env"
30
+ SERVICE_MODE_FILE="${INSTALL_DIR}/.service-mode"
31
+ SERVICE_NAME="langmart-gateway"
32
+
33
+ # Output tracking
34
+ running=false
35
+ port=""
36
+ pid=""
37
+ service_mode=false
38
+
39
+ # Log function that outputs to both console and can be parsed
40
+ log() {
41
+ local level="${2:-INFO}"
42
+ local timestamp=$(date +"%H:%M:%S")
43
+ echo "[$level] $timestamp - $1"
44
+ }
45
+
46
+ # Check if running in service mode
47
+ check_service_mode() {
48
+ if [ -f "$SERVICE_MODE_FILE" ]; then
49
+ local mode=$(cat "$SERVICE_MODE_FILE" 2>/dev/null || echo "")
50
+ if [ "$mode" = "systemd" ]; then
51
+ if systemctl list-unit-files 2>/dev/null | grep -q "^${SERVICE_NAME}.service"; then
52
+ service_mode=true
53
+ return 0
54
+ fi
55
+ fi
56
+ fi
57
+ service_mode=false
58
+ return 1
59
+ }
60
+
61
+ # Detect Node.js binary (prefer isolated installation)
62
+ detect_node() {
63
+ if [ -f "$INSTALL_DIR/node/bin/node" ]; then
64
+ NODE_BIN="$INSTALL_DIR/node/bin/node"
65
+ log "Using isolated Node.js: $($NODE_BIN --version)"
66
+ else
67
+ NODE_BIN="node"
68
+ local version=$(node --version 2>/dev/null || echo "not found")
69
+ log "Using system Node.js: $version"
70
+
71
+ if [[ "$version" != "not found" ]]; then
72
+ major_version=$(echo "$version" | sed 's/v//' | cut -d. -f1)
73
+ if [ "$major_version" -lt 14 ]; then
74
+ log "WARNING: Node.js $version may not support modern JavaScript syntax" "WARN"
75
+ fi
76
+ fi
77
+ fi
78
+ }
79
+
80
+ # Load .env file
81
+ load_env() {
82
+ if [ -f "$ENV_FILE" ]; then
83
+ log "Loading environment from $ENV_FILE"
84
+ set -a
85
+ source "$ENV_FILE"
86
+ set +a
87
+ return 0
88
+ else
89
+ log ".env file not found at $ENV_FILE" "WARN"
90
+ return 1
91
+ fi
92
+ }
93
+
94
+ # Find the correct entry file
95
+ find_entry_file() {
96
+ if [ -f "$INSTALL_DIR/node_modules/langmart-gateway-type3/dist/index-server.js" ]; then
97
+ ENTRY_FILE="$INSTALL_DIR/node_modules/langmart-gateway-type3/dist/index-server.js"
98
+ elif [ -f "$PROJECT_DIR/dist/index-server.js" ]; then
99
+ ENTRY_FILE="$PROJECT_DIR/dist/index-server.js"
100
+ else
101
+ log "Entry file not found!" "ERROR"
102
+ return 1
103
+ fi
104
+ log "Entry file: $ENTRY_FILE"
105
+ return 0
106
+ }
107
+
108
+ # ============================================
109
+ # MAIN SCRIPT
110
+ # ============================================
111
+
112
+ log "=== Gateway Type 3 Start Script ==="
113
+ log "Install directory: $INSTALL_DIR"
114
+
115
+ # Load environment
116
+ load_env
117
+
118
+ # Set defaults
119
+ GATEWAY_PORT="${GATEWAY_PORT:-8083}"
120
+ GATEWAY_API_KEY="${GATEWAY_API_KEY:-}"
121
+ MARKETPLACE_URL="${MARKETPLACE_URL:-ws://localhost:8081}"
122
+ GATEWAY_ID="${GATEWAY_ID:-}"
123
+
124
+ # ============================================
125
+ # CHECK SERVICE MODE
126
+ # ============================================
127
+ check_service_mode
128
+ if [ "$service_mode" = true ]; then
129
+ log "Service mode detected (systemd)"
130
+
131
+ service_status=$(systemctl is-active "$SERVICE_NAME" 2>/dev/null || echo "inactive")
132
+
133
+ if [ "$service_status" = "active" ]; then
134
+ existing_pid=$(lsof -ti:$GATEWAY_PORT 2>/dev/null || true)
135
+ if [ -n "$existing_pid" ]; then
136
+ log "Service already running (PID: $existing_pid)" "SUCCESS"
137
+ echo "RESULT:running=true,port=$GATEWAY_PORT,pid=$existing_pid,mode=service"
138
+ exit 0
139
+ fi
140
+ fi
141
+
142
+ log "Starting via systemctl..."
143
+ if sudo systemctl start "$SERVICE_NAME" 2>/dev/null || systemctl start "$SERVICE_NAME" 2>/dev/null; then
144
+ sleep 3
145
+ existing_pid=$(lsof -ti:$GATEWAY_PORT 2>/dev/null || true)
146
+ if [ -n "$existing_pid" ]; then
147
+ log "Service started successfully (PID: $existing_pid)" "SUCCESS"
148
+ echo "RESULT:running=true,port=$GATEWAY_PORT,pid=$existing_pid,mode=service"
149
+ exit 0
150
+ else
151
+ log "Service start command succeeded but gateway not listening" "ERROR"
152
+ echo "RESULT:running=false,port=,pid=,mode=service"
153
+ exit 1
154
+ fi
155
+ else
156
+ log "Failed to start service (may need sudo)" "ERROR"
157
+ echo "RESULT:running=false,port=,pid=,mode=service"
158
+ exit 1
159
+ fi
29
160
  fi
30
161
 
31
- # Check if dist folder exists
32
- if [ ! -d "$PROJECT_DIR/dist" ]; then
33
- echo -e "${YELLOW}Building TypeScript...${NC}"
34
- cd "$PROJECT_DIR"
35
- npm run build > /dev/null 2>&1 || echo -e "${RED}Build warnings (may be ignored)${NC}"
162
+ # ============================================
163
+ # STANDALONE MODE
164
+ # ============================================
165
+ log "Running in standalone mode"
166
+
167
+ # PRE-FLIGHT CHECK: Required parameters
168
+ log "Checking required parameters..."
169
+
170
+ missing_vars=""
171
+ [ -z "$GATEWAY_API_KEY" ] && missing_vars="$missing_vars GATEWAY_API_KEY"
172
+ [ -z "$MARKETPLACE_URL" ] && missing_vars="$missing_vars MARKETPLACE_URL"
173
+
174
+ if [ -n "$missing_vars" ]; then
175
+ log "Missing required parameters:$missing_vars" "ERROR"
176
+ echo "RESULT:running=false,port=,pid=,mode=standalone"
177
+ exit 1
36
178
  fi
37
179
 
38
- # Change to project directory
39
- cd "$PROJECT_DIR"
40
-
41
- # Set environment variables (use existing or defaults)
42
- export GATEWAY_API_KEY="${GATEWAY_API_KEY:-sk-test-inference-key}"
43
- export MARKETPLACE_URL="${MARKETPLACE_URL:-ws://$HOST_IP:8081}"
44
- export GATEWAY_PORT="${GATEWAY_PORT:-8083}"
45
-
46
- echo -e "${BLUE}Starting Gateway Type 3...${NC}"
47
- echo -e "${CYAN}Environment:${NC}"
48
- echo -e " Port: $GATEWAY_PORT"
49
- echo -e " Marketplace: $MARKETPLACE_URL"
50
- echo -e " API Key: ${GATEWAY_API_KEY:0:10}..."
51
-
52
- # Start gateway with nohup for SSH disconnect protection
53
- nohup node dist/index-server.js > "$LOG_FILE" 2>&1 &
54
- GATEWAY_PID=$!
55
-
56
- # Save PID to file
57
- echo $GATEWAY_PID > "$PID_FILE"
58
-
59
- echo -e "${GREEN}✅ Gateway Type 3 started (PID: $GATEWAY_PID)${NC}"
60
- echo -e "${GREEN}✅ Protected from SSH disconnection (nohup)${NC}"
61
- echo -e "${CYAN}Logs: $LOG_FILE${NC}"
62
- echo -e "${CYAN}PID File: $PID_FILE${NC}"
63
-
64
- # Wait for gateway to start
65
- echo -e "${YELLOW}Waiting for Gateway Type 3 to start...${NC}"
66
- sleep 2
67
-
68
- # Check health
69
- RETRIES=0
70
- MAX_RETRIES=10
71
- while [ $RETRIES -lt $MAX_RETRIES ]; do
72
- if curl -s "http://$HOST_IP:$GATEWAY_PORT/health" > /dev/null 2>&1; then
73
- echo -e "${GREEN}✅ Gateway Type 3 is healthy${NC}"
74
- echo -e "${CYAN}Management API: http://$HOST_IP:$GATEWAY_PORT${NC}"
75
- exit 0
180
+ log "GATEWAY_PORT: $GATEWAY_PORT"
181
+ log "MARKETPLACE_URL: $MARKETPLACE_URL"
182
+ log "GATEWAY_API_KEY: ${GATEWAY_API_KEY:0:8}..."
183
+
184
+ # PRE-FLIGHT CHECK: Already running
185
+ existing_pid=$(lsof -ti:$GATEWAY_PORT 2>/dev/null || true)
186
+ if [ -n "$existing_pid" ]; then
187
+ log "Gateway already running on port $GATEWAY_PORT (PID: $existing_pid)" "SUCCESS"
188
+ echo "RESULT:running=true,port=$GATEWAY_PORT,pid=$existing_pid,mode=standalone"
189
+ exit 0
190
+ fi
191
+ log "Port $GATEWAY_PORT is available" "SUCCESS"
192
+
193
+ # PRE-FLIGHT CHECK: Node.js
194
+ detect_node
195
+
196
+ # PRE-FLIGHT CHECK: Entry file
197
+ find_entry_file || {
198
+ echo "RESULT:running=false,port=,pid=,mode=standalone"
199
+ exit 1
200
+ }
201
+
202
+ # ============================================
203
+ # START GATEWAY
204
+ # ============================================
205
+ log "=== Starting Gateway ==="
206
+
207
+ mkdir -p "$LOG_DIR"
208
+ > "$LOG_FILE"
209
+
210
+ export GATEWAY_PORT GATEWAY_API_KEY MARKETPLACE_URL GATEWAY_ID
211
+
212
+ log "Starting with: $NODE_BIN $ENTRY_FILE"
213
+
214
+ cd "$INSTALL_DIR"
215
+ nohup "$NODE_BIN" "$ENTRY_FILE" >> "$LOG_FILE" 2>&1 &
216
+ gateway_pid=$!
217
+
218
+ echo $gateway_pid > "$PID_FILE"
219
+
220
+ log "Process started with PID: $gateway_pid"
221
+ log "Logs: $LOG_FILE"
222
+
223
+ # VERIFY GATEWAY IS LISTENING
224
+ log "Waiting for gateway to start listening..."
225
+
226
+ max_wait=15
227
+ wait_interval=2
228
+ total_waited=0
229
+ listening=false
230
+
231
+ while [ $total_waited -lt $max_wait ]; do
232
+ sleep $wait_interval
233
+ total_waited=$((total_waited + wait_interval))
234
+
235
+ check_pid=$(lsof -ti:$GATEWAY_PORT 2>/dev/null || true)
236
+ if [ -n "$check_pid" ]; then
237
+ listening=true
238
+ pid="$check_pid"
239
+ break
76
240
  fi
77
- sleep 1
78
- RETRIES=$((RETRIES + 1))
79
- echo -n "."
241
+ log "Waiting... ($total_waited/$max_wait seconds)"
80
242
  done
81
243
 
82
- echo ""
83
- echo -e "${RED}❌ Gateway failed to start within timeout${NC}"
84
- echo -e "${CYAN}Check logs: tail -f $LOG_FILE${NC}"
85
- exit 1
244
+ if [ "$listening" = true ]; then
245
+ log "Gateway confirmed listening on port $GATEWAY_PORT (PID: $pid)" "SUCCESS"
246
+ [ -f "$LOG_FILE" ] && tail -5 "$LOG_FILE" 2>/dev/null || true
247
+ echo "RESULT:running=true,port=$GATEWAY_PORT,pid=$pid,mode=standalone"
248
+ exit 0
249
+ else
250
+ log "Gateway failed to start listening" "ERROR"
251
+ [ -f "$LOG_FILE" ] && cat "$LOG_FILE" 2>/dev/null || true
252
+ echo "RESULT:running=false,port=,pid=,mode=standalone"
253
+ exit 1
254
+ fi