asyx 0.1.2 → 0.2.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.
@@ -0,0 +1,150 @@
1
+ /**
2
+ * MqttControlPlaneTransport
3
+ *
4
+ * Adapter that wraps MqttControlPlaneClient to implement the Transport interface
5
+ * required by MqttCore. This allows us to use MqttControlPlaneClient for connection
6
+ * management while still using MqttCore for the higher-level API.
7
+ */
8
+
9
+ import { MqttControlPlaneClient } from './MqttControlPlaneClient.js';
10
+
11
+ /**
12
+ * Transport adapter that wraps MqttControlPlaneClient.
13
+ * Implements the Transport interface from @asyx/mqtt-core.
14
+ */
15
+ export class MqttControlPlaneTransport {
16
+ /**
17
+ * @param {MqttControlPlaneClient} client
18
+ */
19
+ constructor(client) {
20
+ this.client = client;
21
+ this._messageHandler = null;
22
+ this._connectHandler = null;
23
+ this._disconnectHandler = null;
24
+
25
+ // Store original callbacks to preserve them
26
+ const originalOnConnected = this.client.onConnected;
27
+ const originalOnOffline = this.client.onOffline;
28
+
29
+ // Wire up handlers when client connects (chain with existing callbacks)
30
+ this.client.onConnected = async (mqttClient) => {
31
+ // Wire up message handler (setMessageHandler ensures it's wired on reconnect)
32
+ if (this._messageHandler) {
33
+ this.client.setMessageHandler(this._messageHandler);
34
+ }
35
+
36
+ // Call original callback (set by tunnel.js)
37
+ if (originalOnConnected) {
38
+ await originalOnConnected(mqttClient);
39
+ }
40
+
41
+ // Call Transport connect handler (for MqttCore)
42
+ if (this._connectHandler) {
43
+ this._connectHandler();
44
+ }
45
+ };
46
+
47
+ // Wire up disconnect handler (chain with existing callbacks)
48
+ this.client.onOffline = (reason) => {
49
+ // Call original callback (set by tunnel.js)
50
+ if (originalOnOffline) {
51
+ originalOnOffline(reason);
52
+ }
53
+
54
+ // Call Transport disconnect handler (for MqttCore)
55
+ if (this._disconnectHandler) {
56
+ this._disconnectHandler(new Error(reason));
57
+ }
58
+ };
59
+ }
60
+
61
+ /**
62
+ * Transport interface: connect
63
+ * @param {any} opts - ConnectOptions (ignored, client manages its own connection)
64
+ * @returns {Promise<void>}
65
+ */
66
+ async connect(opts) {
67
+ // Client manages its own connection, just ensure it's connected
68
+ if (!this.client.isOnline()) {
69
+ await this.client.connect();
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Transport interface: end
75
+ * @returns {Promise<void>}
76
+ */
77
+ async end() {
78
+ return this.client.disconnect();
79
+ }
80
+
81
+ /**
82
+ * Transport interface: publish
83
+ * @param {{topic: string, payload: string | Buffer | Uint8Array, qos?: 0 | 1, retain?: boolean}} p
84
+ * @returns {Promise<void>}
85
+ */
86
+ async publish(p) {
87
+ const payload = p.payload instanceof Uint8Array
88
+ ? Buffer.from(p.payload)
89
+ : (typeof p.payload === 'string' ? p.payload : p.payload);
90
+ return this.client.publish(p.topic, payload, { qos: p.qos ?? 0, retain: p.retain ?? false });
91
+ }
92
+
93
+ /**
94
+ * Transport interface: subscribe
95
+ * @param {string} topic
96
+ * @param {0 | 1} [qos=0]
97
+ * @returns {Promise<{topic: string, qos: 0 | 1}>}
98
+ */
99
+ async subscribe(topic, qos = 0) {
100
+ return this.client.subscribe(topic, qos);
101
+ }
102
+
103
+ /**
104
+ * Transport interface: unsubscribe
105
+ * @param {string} topic
106
+ * @returns {Promise<void>}
107
+ */
108
+ async unsubscribe(topic) {
109
+ return this.client.unsubscribe(topic);
110
+ }
111
+
112
+ /**
113
+ * Transport interface: onMessage
114
+ * @param {(message: {topic: string, payload: Uint8Array}) => void} cb
115
+ */
116
+ onMessage(cb) {
117
+ this._messageHandler = cb;
118
+ // Set message handler on client (will be wired on connect/reconnect)
119
+ this.client.setMessageHandler(cb);
120
+ }
121
+
122
+ /**
123
+ * Transport interface: onConnect
124
+ * @param {() => void} cb
125
+ */
126
+ onConnect(cb) {
127
+ this._connectHandler = cb;
128
+ // If already connected, call immediately
129
+ if (this.client.isOnline()) {
130
+ cb();
131
+ }
132
+ }
133
+
134
+ /**
135
+ * Transport interface: onDisconnect
136
+ * @param {(err?: unknown) => void} cb
137
+ */
138
+ onDisconnect(cb) {
139
+ this._disconnectHandler = cb;
140
+ }
141
+
142
+ /**
143
+ * Expose client for helpers that need direct access
144
+ * @returns {MqttControlPlaneClient}
145
+ */
146
+ getClient() {
147
+ return this.client;
148
+ }
149
+ }
150
+
package/src/lib/logger.js CHANGED
@@ -8,14 +8,18 @@ const LEVEL_ORDER = { error: 40, warn: 30, info: 20, debug: 10 };
8
8
  function normalizeLevel(value) {
9
9
  const v = String(value || '').trim().toLowerCase();
10
10
  if (v in LEVEL_ORDER) return v;
11
- return 'info';
11
+ // QPA-CLI-10: Default to warn for quiet mode (suppress info/debug telemetry, show warn/error)
12
+ // Users can set LOG_LEVEL=info to see structured telemetry logs
13
+ return 'warn';
12
14
  }
13
15
 
14
- const ENV_LEVEL = normalizeLevel(process.env.ASYX_LOG_LEVEL);
16
+ // QPA-CLI-10: Support both ASYX_LOG_LEVEL and LOG_LEVEL env vars
17
+ const ENV_LEVEL = normalizeLevel(process.env.ASYX_LOG_LEVEL || process.env.LOG_LEVEL);
15
18
 
16
19
  function shouldEmit(level) {
17
- const desired = LEVEL_ORDER[ENV_LEVEL] ?? LEVEL_ORDER.info;
18
- const actual = LEVEL_ORDER[normalizeLevel(level)] ?? LEVEL_ORDER.info;
20
+ // QPA-CLI-10: Default to warn level (quiet mode - suppress info/debug telemetry)
21
+ const desired = LEVEL_ORDER[ENV_LEVEL] ?? LEVEL_ORDER.warn;
22
+ const actual = LEVEL_ORDER[normalizeLevel(level)] ?? LEVEL_ORDER.error; // Default actual to error if invalid
19
23
  return actual >= desired;
20
24
  }
21
25
 
@@ -7,10 +7,11 @@
7
7
  */
8
8
 
9
9
  export class AwaiterMap {
10
- constructor(maxSize = 100) {
10
+ constructor(maxSize = 100, logger = null) {
11
11
  this.maxSize = maxSize;
12
12
  this.awaiters = new Map();
13
13
  this.nextId = 1;
14
+ this.logger = logger; // QPA-CLI-10: Optional logger for quiet mode
14
15
  }
15
16
 
16
17
  /**
@@ -58,14 +59,55 @@ export class AwaiterMap {
58
59
  processMessage(message) {
59
60
  let resolved = false;
60
61
 
62
+ // Log open_ack messages for debugging awaiter matching
63
+ const isOpenAck = message.payload?.type === 'open_ack';
64
+ const requestId = message.payload?.requestId;
65
+
66
+ if (isOpenAck && requestId) {
67
+ // QPA-CLI-10: Use logger at debug level for quiet mode
68
+ if (this.logger) {
69
+ this.logger.debug('awaiter.open_ack.received', {
70
+ requestId,
71
+ topic: message.topic,
72
+ pendingAwaiters: this.awaiters.size,
73
+ awaiterIds: Array.from(this.awaiters.keys())
74
+ });
75
+ }
76
+ }
77
+
61
78
  for (const [id, awaiter] of this.awaiters) {
62
79
  try {
63
- if (awaiter.criteria(message)) {
80
+ const matched = awaiter.criteria(message);
81
+
82
+ if (isOpenAck && requestId) {
83
+ // QPA-CLI-10: Use logger at debug level for quiet mode
84
+ if (this.logger) {
85
+ this.logger.debug('awaiter.open_ack.checked', {
86
+ requestId,
87
+ awaiterId: id,
88
+ matched,
89
+ topic: message.topic
90
+ });
91
+ }
92
+ }
93
+
94
+ if (matched) {
64
95
  // Clear timeout and resolve
65
96
  clearTimeout(awaiter.timeoutId);
66
97
  this.awaiters.delete(id);
67
98
  awaiter.resolve(message);
68
99
  resolved = true;
100
+
101
+ if (isOpenAck && requestId) {
102
+ // QPA-CLI-10: Use logger at debug level for quiet mode
103
+ if (this.logger) {
104
+ this.logger.debug('awaiter.open_ack.resolved', {
105
+ requestId,
106
+ awaiterId: id,
107
+ topic: message.topic
108
+ });
109
+ }
110
+ }
69
111
  }
70
112
  } catch (error) {
71
113
  // Criteria function threw an error - reject and clean up
@@ -73,6 +115,31 @@ export class AwaiterMap {
73
115
  this.awaiters.delete(id);
74
116
  awaiter.reject(error);
75
117
  resolved = true;
118
+
119
+ if (isOpenAck && requestId) {
120
+ // QPA-CLI-10: Use logger at debug level for quiet mode
121
+ if (this.logger) {
122
+ this.logger.debug('awaiter.open_ack.criteria_error', {
123
+ requestId,
124
+ awaiterId: id,
125
+ error: error.message,
126
+ topic: message.topic
127
+ });
128
+ }
129
+ }
130
+ }
131
+ }
132
+
133
+ if (isOpenAck && requestId && !resolved) {
134
+ // QPA-CLI-10: Use logger at debug level for quiet mode (no_match is expected when awaiter already resolved)
135
+ if (this.logger) {
136
+ this.logger.debug('awaiter.open_ack.no_match', {
137
+ requestId,
138
+ topic: message.topic,
139
+ pendingAwaiters: this.awaiters.size,
140
+ payloadType: message.payload?.type,
141
+ payloadRequestId: message.payload?.requestId
142
+ });
76
143
  }
77
144
  }
78
145
 
@@ -96,6 +163,29 @@ export class AwaiterMap {
96
163
  };
97
164
  }
98
165
 
166
+ /**
167
+ * Cancel awaiters that match a test criteria
168
+ * @param {Function} testCriteria - Function that returns true if an awaiter should be cancelled
169
+ * @returns {number} Number of awaiters cancelled
170
+ */
171
+ cancelByCriteria(testCriteria) {
172
+ let cancelled = 0;
173
+ for (const [id, awaiter] of this.awaiters) {
174
+ try {
175
+ if (testCriteria(awaiter)) {
176
+ clearTimeout(awaiter.timeoutId);
177
+ this.awaiters.delete(id);
178
+ awaiter.reject(new Error(`Awaiter ${id} cancelled by criteria`));
179
+ cancelled++;
180
+ }
181
+ } catch (error) {
182
+ // Test criteria threw an error - skip this awaiter
183
+ continue;
184
+ }
185
+ }
186
+ return cancelled;
187
+ }
188
+
99
189
  /**
100
190
  * Clear all awaiters (for cleanup)
101
191
  */
@@ -1,5 +1,25 @@
1
1
  import { AnyEvt as AnyEvtSchema } from "./schemas.js";
2
- import { setAssignment } from "../../state/assignment.js";
2
+ import { setAssignment, getAssignment } from "../../state/assignment.js";
3
+ import logger from "../../lib/logger.js";
4
+
5
+ /**
6
+ * Format milliseconds to human-readable hours:minutes
7
+ * @param {number} ms - Milliseconds
8
+ * @returns {string} Formatted string like "1h 30m" or "45m"
9
+ */
10
+ function formatLeaseDuration(ms) {
11
+ const totalMinutes = Math.floor(ms / 60000);
12
+ const hours = Math.floor(totalMinutes / 60);
13
+ const minutes = totalMinutes % 60;
14
+
15
+ if (hours > 0 && minutes > 0) {
16
+ return `${hours}h ${minutes}m`;
17
+ } else if (hours > 0) {
18
+ return `${hours}h`;
19
+ } else {
20
+ return `${minutes}m`;
21
+ }
22
+ }
3
23
 
4
24
  const registry = {
5
25
  async setup_required(e) {
@@ -12,7 +32,6 @@ const registry = {
12
32
  },
13
33
 
14
34
  async open_ack(e) {
15
- console.log(`🔍 open_ack handler called with requestId: ${e.requestId}`);
16
35
  // Normalize legacy format to canonical format
17
36
  let data = e.data;
18
37
 
@@ -32,34 +51,124 @@ const registry = {
32
51
  };
33
52
  }
34
53
 
35
- // Build relay URL
36
- const url = `${data.assignment.proto}://${data.assignment.fqdn}${data.assignment.path}`;
54
+ // QPA-CLI-11: Store QuickPass info in assignment for vault UX messaging
55
+ // Suppress QP: enabled and Ack received messages - they'll be consolidated in final tunnel.active message
56
+ const quickpassSlug = data.quickpass?.slug || null;
57
+ if (quickpassSlug) {
58
+ logger.info("qp.enabled", { group: quickpassSlug });
59
+ }
60
+
61
+ // Build relay URL with fallbacks for missing fields
62
+ // TCP-S4: Add fallbacks to prevent malformed URLs if TCP assignments omit fields
63
+ const proto = data.assignment?.proto || 'wss';
64
+ const fqdn = data.assignment?.fqdn || data.fqdn || 'relay.unknown';
65
+ // TCP-S4: Always use /tcp for TCP tunnels, /agent for HTTP tunnels
66
+ // Detect TCP by checking for publicPort (TCP-specific) or proto === 'tcp'
67
+ const isTcpTunnel = data.assignment?.publicPort !== undefined ||
68
+ data.assignment?.proto === 'tcp' ||
69
+ data.publicPort !== undefined;
70
+ // Always override path for TCP tunnels, regardless of what Lambda returns
71
+ const path = isTcpTunnel ? '/tcp' : (data.assignment?.path || '/agent');
72
+ const url = `${proto}://${fqdn}${path}`;
73
+
74
+ // Log warning if fallbacks were used
75
+ if (!data.assignment?.proto || !data.assignment?.fqdn || !data.assignment?.path) {
76
+ logger.warn('open_ack.relay_url_fallback', {
77
+ requestId: e.requestId,
78
+ proto: data.assignment?.proto || 'missing',
79
+ fqdn: data.assignment?.fqdn || 'missing',
80
+ path: data.assignment?.path || 'missing',
81
+ constructedUrl: url
82
+ });
83
+ }
37
84
 
38
85
  // Store assignment in memory (never to disk)
39
86
  const leaseId = e.correlationId || data.leaseId || data.assignment?.leaseId || null;
40
- console.log('🔍 leaseId from ack:', leaseId);
87
+ logger.debug("open_ack.lease_id", { requestId: e.requestId, leaseId });
41
88
 
89
+ // Check if this is a refresh (existing assignment) or initial connection
90
+ const existingAssignment = getAssignment();
91
+ const isRefresh = existingAssignment !== null;
92
+
93
+ // TCP-S3: Extract TCP-specific fields from assignment
94
+ // E3-S8: Extract SRV status for Minecraft tunnels
95
+ // Reuse fqdn from above (already declared for relayUrl construction)
96
+ const tcpAliasFqdn = data.assignment?.tcpAliasFqdn || data.tcpAliasFqdn || null;
97
+ const publicPort = data.assignment?.publicPort || data.publicPort || null;
98
+ const srvProvisioned = data.assignment?.srvProvisioned === true;
99
+ const srvFqdn = data.assignment?.srvFqdn || null;
100
+ const warnings = data.warnings || data.assignment?.warnings || [];
101
+
42
102
  setAssignment({
43
103
  requestId: e.requestId,
44
104
  relayId: data.relayId,
45
105
  relayUrl: url,
46
106
  jwt: data.assignment.jwt, // Stored in memory only
47
107
  leaseMs: data.leaseMs,
48
- leaseId
108
+ leaseId,
109
+ quickpassSlug, // QPA-CLI-11: Store QuickPass slug for vault UX messaging
110
+ // TCP-S3: Store TCP-specific fields
111
+ tcpAliasFqdn,
112
+ publicPort,
113
+ fqdn,
114
+ // E3-S8: Store SRV provisioning status
115
+ srvProvisioned,
116
+ srvFqdn,
117
+ warnings
49
118
  });
50
119
 
51
- console.log(`🔍 Assignment stored for requestId: ${e.requestId}`);
120
+ logger.debug("open_ack.assignment_stored", {
121
+ requestId: e.requestId,
122
+ isRefresh,
123
+ quickpassSlug,
124
+ tcpAliasFqdn,
125
+ publicPort,
126
+ hasWarnings: warnings.length > 0
127
+ });
52
128
 
53
- // Print concise success message (no JWT logging)
54
- process.stdout.write(
55
- `✅ Ack received — relay=${data.relayId} leaseMs=${data.leaseMs}\n`
56
- );
129
+ // TCP-S3: Handle TCP_ALIAS_UNAVAILABLE warning (warn-only, don't fail)
130
+ if (warnings.includes('TCP_ALIAS_UNAVAILABLE') || warnings.some(w => w.code === 'TCP_ALIAS_UNAVAILABLE')) {
131
+ logger.warn('tcp.alias.unavailable', {
132
+ requestId: e.requestId,
133
+ fqdn,
134
+ publicPort
135
+ });
136
+ }
137
+
138
+ // QPA-CLI-11: Suppress all intermediate messages (QP: enabled, Ack received)
139
+ // These will be consolidated into the final vault UX sequence
57
140
  },
58
141
 
59
142
  async open_reject(e) {
60
143
  // Print rejection reason and keep process alive.
61
144
  const d = e.data;
62
145
  const reason = d.reason ? ` (${d.reason})` : "";
146
+
147
+ // QPA-04: Handle invalid_secgroup rejection
148
+ if (d.reason === 'invalid_secgroup' || d.reason === 'INVALID_SECGROUP') {
149
+ // Extract slug from requestId context or data if available
150
+ // Note: The slug was sent in the cmd/open payload, but we don't have direct access here
151
+ // The coordinator should include it in the rejection message, but for now we'll use a generic message
152
+ const slug = d.slug || d.secGroupSlug || 'unknown';
153
+ process.stderr.write(`QuickPass group "${slug}" not found. Re-run \`asyx tunnel\` with a valid group.\n`);
154
+ // Exit with code 1 before opening tunnel
155
+ process.exit(1);
156
+ }
157
+
158
+ // TCP-S3: Handle TCP-specific error codes
159
+ if (d.reason === 'TCP_PORT_CAPACITY_EXHAUSTED' || d.reason === 'tcp_port_capacity_exhausted') {
160
+ process.stderr.write(`Relay TCP port capacity exhausted. Please retry later.\n`);
161
+ process.exit(1);
162
+ }
163
+
164
+ if (d.reason === 'TENANT_TCP_LEASE_LIMIT_REACHED' || d.reason === 'tenant_tcp_lease_limit_reached') {
165
+ const relayId = d.relayId || 'unknown';
166
+ process.stderr.write(`Tenant TCP lease limit reached on relay ${relayId}\n`);
167
+ process.exit(1);
168
+ }
169
+
170
+ // TCP_ALIAS_UNAVAILABLE is handled as a warning in open_ack, not a rejection
171
+
63
172
  process.stdout.write(
64
173
  `❌ Connection rejected${reason}\n`
65
174
  );
@@ -14,7 +14,8 @@ import { AwaiterMap } from './awaiter-map.js';
14
14
 
15
15
  export class MessageIngress {
16
16
  constructor(options = {}) {
17
- this.awaiterMap = new AwaiterMap(options.maxAwaiters || 100);
17
+ // QPA-CLI-10: Pass logger to AwaiterMap for quiet mode
18
+ this.awaiterMap = new AwaiterMap(options.maxAwaiters || 100, options.logger || null);
18
19
  this.dispatcher = null;
19
20
  this.observability = options.observability || false;
20
21
  this.messageCounter = 0;
@@ -38,6 +39,15 @@ export class MessageIngress {
38
39
  return this.awaiterMap.register(criteria, timeoutMs);
39
40
  }
40
41
 
42
+ /**
43
+ * Cancel awaiters that match a test criteria
44
+ * @param {Function} testCriteria - Function that returns true if an awaiter should be cancelled
45
+ * @returns {number} Number of awaiters cancelled
46
+ */
47
+ cancelAwaitersByCriteria(testCriteria) {
48
+ return this.awaiterMap.cancelByCriteria(testCriteria);
49
+ }
50
+
41
51
  /**
42
52
  * Main ingress handler - processes all incoming MQTT messages
43
53
  * @param {Object} message - Raw MQTT message from transport
@@ -22,6 +22,15 @@ export function setAssignment(assignment) {
22
22
  jwt: assignment.jwt, // Stored in memory only
23
23
  leaseMs: assignment.leaseMs,
24
24
  leaseId: assignment.leaseId, // CLI-IMG-WSReconnect: Store leaseId for JWT refresh
25
+ quickpassSlug: assignment.quickpassSlug || null, // QPA-CLI-11: Store QuickPass slug for vault UX messaging
26
+ // TCP-S3: Store TCP-specific fields
27
+ tcpAliasFqdn: assignment.tcpAliasFqdn || null,
28
+ publicPort: assignment.publicPort || null,
29
+ fqdn: assignment.fqdn || null,
30
+ // E3-S8: Store SRV provisioning status
31
+ srvProvisioned: assignment.srvProvisioned === true,
32
+ srvFqdn: assignment.srvFqdn || null,
33
+ warnings: assignment.warnings || [],
25
34
  timestamp: Date.now(),
26
35
  lastRefreshMs: undefined,
27
36
  lastRefreshIso: undefined,