asyx 0.0.2 → 0.1.1

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,90 @@
1
+ import { AnyEvt as AnyEvtSchema } from "./schemas.js";
2
+ import { setAssignment } from "../../state/assignment.js";
3
+
4
+ const registry = {
5
+ async setup_required(e) {
6
+ // Minimal user-facing message; CLI should exit(2)
7
+ // Do not add logs; leave control to caller via thrown Error with code.
8
+ const reason = e.data?.reason ? ` (${e.data.reason})` : "";
9
+ const err = new Error(`Please run "asyx setup"${reason}`);
10
+ err.code = "SETUP_REQUIRED";
11
+ throw err;
12
+ },
13
+
14
+ async open_ack(e) {
15
+ console.log(`🔍 open_ack handler called with requestId: ${e.requestId}`);
16
+ // Normalize legacy format to canonical format
17
+ let data = e.data;
18
+
19
+ // Legacy format: { data: { jwt, relayId, leaseMs } }
20
+ // Canonical format: { data: { relayId, leaseMs, assignment: { jwt, fqdn, proto, path, ... } } }
21
+ if (data.jwt && !data.assignment) {
22
+ // Transform legacy to canonical
23
+ data = {
24
+ relayId: data.relayId,
25
+ leaseMs: data.leaseMs,
26
+ assignment: {
27
+ jwt: data.jwt,
28
+ fqdn: 'relay.customer.example', // Default fallback
29
+ proto: 'wss',
30
+ path: '/agent'
31
+ }
32
+ };
33
+ }
34
+
35
+ // Build relay URL
36
+ const url = `${data.assignment.proto}://${data.assignment.fqdn}${data.assignment.path}`;
37
+
38
+ // Store assignment in memory (never to disk)
39
+ const leaseId = e.correlationId || data.leaseId || data.assignment?.leaseId || null;
40
+ console.log('🔍 leaseId from ack:', leaseId);
41
+
42
+ setAssignment({
43
+ requestId: e.requestId,
44
+ relayId: data.relayId,
45
+ relayUrl: url,
46
+ jwt: data.assignment.jwt, // Stored in memory only
47
+ leaseMs: data.leaseMs,
48
+ leaseId
49
+ });
50
+
51
+ console.log(`🔍 Assignment stored for requestId: ${e.requestId}`);
52
+
53
+ // Print concise success message (no JWT logging)
54
+ process.stdout.write(
55
+ `✅ Ack received — relay=${data.relayId} leaseMs=${data.leaseMs}\n`
56
+ );
57
+ },
58
+
59
+ async open_reject(e) {
60
+ // Print rejection reason and keep process alive.
61
+ const d = e.data;
62
+ const reason = d.reason ? ` (${d.reason})` : "";
63
+ process.stdout.write(
64
+ `❌ Connection rejected${reason}\n`
65
+ );
66
+ },
67
+
68
+ async error(e) {
69
+ const d = e.data || {};
70
+ const err = new Error(d.msg || "Command failed");
71
+ err.code = `ERROR_${String(d.code || "UNKNOWN").toUpperCase()}`;
72
+ throw err;
73
+ },
74
+ };
75
+
76
+ export function getHandler(type) {
77
+ return registry[type];
78
+ }
79
+
80
+ // Safe parse helper the caller can reuse if needed
81
+ export function parseAny(raw) {
82
+ try {
83
+ const txt = typeof raw === "string" ? raw : new TextDecoder().decode(raw);
84
+ const json = JSON.parse(txt);
85
+ const parsed = AnyEvtSchema.safeParse(json);
86
+ return parsed.success ? parsed.data : null;
87
+ } catch (e) {
88
+ return null;
89
+ }
90
+ }
@@ -0,0 +1,14 @@
1
+ import { parseAny, getHandler } from "./handlers.js";
2
+
3
+ export async function dispatch(parsedMessage) {
4
+ // Extract the parsed payload from the message object
5
+ const payload = parsedMessage.payload;
6
+ if (!payload) return; // No payload — ignore
7
+
8
+ // The payload is already parsed JSON, so we can use it directly
9
+ const evt = payload;
10
+ if (!evt.type) return; // No type — ignore
11
+ const handler = getHandler(evt.type);
12
+ if (!handler) return; // Unknown type — ignore
13
+ return handler(evt);
14
+ }
@@ -0,0 +1,58 @@
1
+ import { z } from "zod";
2
+
3
+ export const Envelope = z.object({
4
+ type: z.enum(["setup_required","open_ack","open_reject","error"]),
5
+ v: z.literal(1),
6
+ requestId: z.string().min(1),
7
+ ts: z.number().int().positive(),
8
+ data: z.unknown(),
9
+ });
10
+
11
+ export const SetupRequired = Envelope.extend({
12
+ type: z.literal("setup_required"),
13
+ data: z.object({ reason: z.string().optional() }),
14
+ });
15
+
16
+ export const OpenAck = Envelope.extend({
17
+ type: z.literal("open_ack"),
18
+ data: z.object({
19
+ relayId: z.string().min(1),
20
+ leaseMs: z.number().int().positive(),
21
+ assignment: z.object({
22
+ jwt: z.string().min(10),
23
+ fqdn: z.string().min(1),
24
+ proto: z.string().min(1),
25
+ path: z.string().min(1),
26
+ kid: z.string().optional(),
27
+ alg: z.string().optional(),
28
+ exp: z.number().optional(),
29
+ }),
30
+ }),
31
+ });
32
+
33
+ // Legacy OpenAck schema for backward compatibility
34
+ export const OpenAckLegacy = Envelope.extend({
35
+ type: z.literal("open_ack"),
36
+ data: z.object({
37
+ relayId: z.string().min(1),
38
+ jwt: z.string().min(10),
39
+ leaseMs: z.number().int().positive(),
40
+ }),
41
+ });
42
+
43
+ export const OpenReject = Envelope.extend({
44
+ type: z.literal("open_reject"),
45
+ data: z.object({
46
+ reason: z.string().min(1),
47
+ }),
48
+ });
49
+
50
+ export const ErrorEvt = Envelope.extend({
51
+ type: z.enum(["error"]),
52
+ data: z.object({
53
+ code: z.string().min(1),
54
+ msg: z.string().optional(),
55
+ }),
56
+ });
57
+
58
+ export const AnyEvt = z.union([SetupRequired, OpenAck, OpenAckLegacy, OpenReject, ErrorEvt]);
@@ -0,0 +1,172 @@
1
+ /**
2
+ * Single Ingress Message Handler
3
+ *
4
+ * Provides a single point of entry for all MQTT messages that:
5
+ * 1. Parses messages once
6
+ * 2. Resolves awaiters for request/response flows
7
+ * 3. Always forwards messages to the CP-3F dispatcher
8
+ *
9
+ * This eliminates the handler-order race that prevents CP-3F envelopes
10
+ * from being processed and establishes the pattern for future stories.
11
+ */
12
+
13
+ import { AwaiterMap } from './awaiter-map.js';
14
+
15
+ export class MessageIngress {
16
+ constructor(options = {}) {
17
+ this.awaiterMap = new AwaiterMap(options.maxAwaiters || 100);
18
+ this.dispatcher = null;
19
+ this.observability = options.observability || false;
20
+ this.messageCounter = 0;
21
+ }
22
+
23
+ /**
24
+ * Set the CP-3F event dispatcher
25
+ * @param {Function} dispatcher - The dispatchEvt function
26
+ */
27
+ setDispatcher(dispatcher) {
28
+ this.dispatcher = dispatcher;
29
+ }
30
+
31
+ /**
32
+ * Register an awaiter for request/response correlation
33
+ * @param {Function} criteria - Function that returns true if message matches
34
+ * @param {number} timeoutMs - Timeout in milliseconds
35
+ * @returns {Promise} Promise that resolves with the matching message
36
+ */
37
+ registerAwaiter(criteria, timeoutMs = 5000) {
38
+ return this.awaiterMap.register(criteria, timeoutMs);
39
+ }
40
+
41
+ /**
42
+ * Main ingress handler - processes all incoming MQTT messages
43
+ * @param {Object} message - Raw MQTT message from transport
44
+ */
45
+ async handleMessage(message) {
46
+ const msgId = ++this.messageCounter;
47
+ const ts = Date.now();
48
+ const sizeBytes = message.payload ? message.payload.length : 0;
49
+
50
+ // Parse message once
51
+ let parsedMessage;
52
+ let parseStatus = 'success';
53
+
54
+ try {
55
+ const raw = message.payload;
56
+ const buffer =
57
+ typeof raw === 'string' ? Buffer.from(raw, 'utf8')
58
+ : Buffer.isBuffer(raw) ? raw
59
+ : ArrayBuffer.isView(raw) ? Buffer.from(raw.buffer, raw.byteOffset, raw.byteLength)
60
+ : raw instanceof ArrayBuffer ? Buffer.from(raw)
61
+ : null;
62
+
63
+ let parsedPayload;
64
+ if (buffer) {
65
+ try {
66
+ parsedPayload = JSON.parse(buffer.toString('utf8'));
67
+ } catch {
68
+ parseStatus = 'json_parse_error';
69
+ }
70
+ }
71
+
72
+ parsedMessage = {
73
+ topic: message.topic,
74
+ payload: parsedPayload,
75
+ raw: buffer,
76
+ sizeBytes,
77
+ msgId,
78
+ ts
79
+ };
80
+ } catch (error) {
81
+ parseStatus = 'parse_error';
82
+ parsedMessage = {
83
+ topic: message.topic,
84
+ payload: undefined,
85
+ raw: message.payload,
86
+ sizeBytes,
87
+ msgId,
88
+ ts,
89
+ error: error.message
90
+ };
91
+ }
92
+
93
+ // Log ingress (CP-5 ready)
94
+ if (this.observability) {
95
+ console.log(`[ingress] ts=${ts} msgId=${msgId} topic=${parsedMessage.topic} parseStatus=${parseStatus} sizeBytes=${sizeBytes}`);
96
+ }
97
+
98
+ // Check awaiters and resolve any matching promises
99
+ const awaiterResolved = this.awaiterMap.processMessage(parsedMessage);
100
+
101
+ // Always dispatch to CP-3F dispatcher (non-exclusive broadcast)
102
+ if (this.dispatcher) {
103
+ try {
104
+ await this.dispatcher(parsedMessage);
105
+
106
+ // Log dispatch completion (CP-5 ready)
107
+ if (this.observability) {
108
+ console.log(`[dispatch] ts=${Date.now()} msgId=${msgId} dispatched=true`);
109
+ }
110
+ } catch (error) {
111
+ // Log dispatch error but don't crash
112
+ if (this.observability) {
113
+ console.log(`[dispatch] ts=${Date.now()} msgId=${msgId} dispatched=false error=${error.message}`);
114
+ }
115
+
116
+ // Re-throw dispatcher errors (they contain business logic like exit codes)
117
+ throw error;
118
+ }
119
+ }
120
+
121
+ return {
122
+ msgId,
123
+ awaiterResolved,
124
+ parseStatus,
125
+ sizeBytes
126
+ };
127
+ }
128
+
129
+ /**
130
+ * Get statistics about the ingress system
131
+ * @returns {Object} Statistics object
132
+ */
133
+ getStats() {
134
+ return {
135
+ messageCounter: this.messageCounter,
136
+ awaiterStats: this.awaiterMap.getStats(),
137
+ hasDispatcher: !!this.dispatcher,
138
+ observabilityEnabled: this.observability
139
+ };
140
+ }
141
+
142
+ /**
143
+ * Clear all awaiters (for cleanup)
144
+ */
145
+ clear() {
146
+ this.awaiterMap.clear();
147
+ }
148
+
149
+ /**
150
+ * Create a session ID awaiter (backward compatibility)
151
+ * @param {string} sessionId - Session ID to match
152
+ * @param {string} expectedTopic - Expected topic pattern
153
+ * @param {number} timeoutMs - Timeout in milliseconds
154
+ * @returns {Promise} Promise that resolves with the matching message
155
+ */
156
+ awaitSessionId(sessionId, expectedTopic, timeoutMs = 5000) {
157
+ const criteria = AwaiterMap.createSessionIdCriteria(sessionId, expectedTopic);
158
+ return this.registerAwaiter(criteria, timeoutMs);
159
+ }
160
+
161
+ /**
162
+ * Create a correlation ID awaiter (future use)
163
+ * @param {string} correlationId - Correlation ID to match
164
+ * @param {string} expectedTopic - Expected topic pattern
165
+ * @param {number} timeoutMs - Timeout in milliseconds
166
+ * @returns {Promise} Promise that resolves with the matching message
167
+ */
168
+ awaitCorrelationId(correlationId, expectedTopic, timeoutMs = 5000) {
169
+ const criteria = AwaiterMap.createCorrelationIdCriteria(correlationId, expectedTopic);
170
+ return this.registerAwaiter(criteria, timeoutMs);
171
+ }
172
+ }
@@ -0,0 +1,156 @@
1
+ // In-memory assignment store for JWT and relay metadata
2
+ // Never writes to disk - memory only
3
+
4
+ let currentAssignment = null;
5
+ const assignmentWaiters = new Map();
6
+
7
+ /**
8
+ * Set the current assignment with JWT and relay metadata
9
+ * @param {Object} assignment - Assignment data
10
+ * @param {string} assignment.requestId - Request ID
11
+ * @param {string} assignment.relayId - Relay ID
12
+ * @param {string} assignment.relayUrl - Relay URL
13
+ * @param {string} assignment.jwt - JWT token (stored in memory only)
14
+ * @param {number} assignment.leaseMs - Lease duration in milliseconds
15
+ * @param {string} assignment.leaseId - Lease ID for JWT refresh (optional)
16
+ */
17
+ export function setAssignment(assignment) {
18
+ currentAssignment = {
19
+ requestId: assignment.requestId,
20
+ relayId: assignment.relayId,
21
+ relayUrl: assignment.relayUrl,
22
+ jwt: assignment.jwt, // Stored in memory only
23
+ leaseMs: assignment.leaseMs,
24
+ leaseId: assignment.leaseId, // CLI-IMG-WSReconnect: Store leaseId for JWT refresh
25
+ timestamp: Date.now(),
26
+ lastRefreshMs: undefined,
27
+ lastRefreshIso: undefined,
28
+ lastRefreshDeltaMs: undefined
29
+ };
30
+ // Notify any waiters that are tracking this requestId
31
+ if (assignment.requestId && assignmentWaiters.size > 0) {
32
+ const waiters = assignmentWaiters.get(assignment.requestId);
33
+ if (waiters && waiters.length) {
34
+ assignmentWaiters.delete(assignment.requestId);
35
+ for (const waiter of waiters) {
36
+ clearTimeout(waiter.timer);
37
+ try {
38
+ waiter.resolve({ ...currentAssignment });
39
+ } catch {
40
+ // Ignore waiter resolution errors; they should not impact CLI flow
41
+ }
42
+ }
43
+ }
44
+ }
45
+ }
46
+
47
+ /**
48
+ * Get the current assignment
49
+ * @returns {Object|null} Current assignment or null if none set
50
+ */
51
+ export function getAssignment() {
52
+ return currentAssignment ? { ...currentAssignment } : null;
53
+ }
54
+
55
+ /**
56
+ * Clear the current assignment
57
+ */
58
+ export function clearAssignment() {
59
+ currentAssignment = null;
60
+ // Reject all outstanding waiters to avoid dangling promises
61
+ if (assignmentWaiters.size > 0) {
62
+ for (const [, waiters] of assignmentWaiters) {
63
+ for (const waiter of waiters) {
64
+ clearTimeout(waiter.timer);
65
+ try {
66
+ waiter.reject(new Error("Assignment cleared before completion"));
67
+ } catch {
68
+ // Ignore waiter rejections; consumers can handle silently
69
+ }
70
+ }
71
+ }
72
+ assignmentWaiters.clear();
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Check if an assignment exists
78
+ * @returns {boolean} True if assignment exists
79
+ */
80
+ export function hasAssignment() {
81
+ return currentAssignment !== null;
82
+ }
83
+
84
+ /**
85
+ * Wait until an assignment with the specified requestId is available.
86
+ * @param {string} requestId - Request ID to wait for
87
+ * @param {number} [timeoutMs=10000] - Timeout before rejecting
88
+ * @returns {Promise<Object>} resolves with the assignment snapshot
89
+ */
90
+ export function waitForAssignment(requestId, timeoutMs = 10000) {
91
+ if (!requestId) {
92
+ return Promise.reject(new Error("waitForAssignment requires a requestId"));
93
+ }
94
+
95
+ if (currentAssignment && currentAssignment.requestId === requestId) {
96
+ return Promise.resolve({ ...currentAssignment });
97
+ }
98
+
99
+ return new Promise((resolve, reject) => {
100
+ const entry = {
101
+ resolve,
102
+ reject,
103
+ timer: setTimeout(() => {
104
+ // Timeout - remove from waiter list and reject
105
+ const queue = assignmentWaiters.get(requestId);
106
+ if (queue) {
107
+ const idx = queue.indexOf(entry);
108
+ if (idx >= 0) queue.splice(idx, 1);
109
+ if (queue.length === 0) assignmentWaiters.delete(requestId);
110
+ }
111
+ reject(new Error(`Assignment ${requestId} not received within ${timeoutMs}ms`));
112
+ }, timeoutMs),
113
+ };
114
+
115
+ const queue = assignmentWaiters.get(requestId);
116
+ if (queue) {
117
+ queue.push(entry);
118
+ } else {
119
+ assignmentWaiters.set(requestId, [entry]);
120
+ }
121
+ });
122
+ }
123
+
124
+ /**
125
+ * Get assignment metadata (without JWT for logging)
126
+ * @returns {Object|null} Assignment metadata or null
127
+ */
128
+ export function getAssignmentMetadata() {
129
+ if (!currentAssignment) return null;
130
+
131
+ return {
132
+ requestId: currentAssignment.requestId,
133
+ relayId: currentAssignment.relayId,
134
+ relayUrl: currentAssignment.relayUrl,
135
+ leaseMs: currentAssignment.leaseMs,
136
+ leaseId: currentAssignment.leaseId,
137
+ timestamp: currentAssignment.timestamp,
138
+ lastRefreshIso: currentAssignment.lastRefreshIso,
139
+ lastRefreshDeltaMs: currentAssignment.lastRefreshDeltaMs
140
+ };
141
+ }
142
+
143
+ /**
144
+ * Record a successful refresh in the assignment cache and return delta ms since last refresh (or since initial assignment if none).
145
+ * @param {number} [nowMs]
146
+ * @returns {number} delta milliseconds since last refresh or initial assignment
147
+ */
148
+ export function recordRefresh(nowMs = Date.now()) {
149
+ if (!currentAssignment) return 0;
150
+ const prev = typeof currentAssignment.lastRefreshMs === 'number' ? currentAssignment.lastRefreshMs : currentAssignment.timestamp;
151
+ const delta = nowMs - prev;
152
+ currentAssignment.lastRefreshMs = nowMs;
153
+ currentAssignment.lastRefreshIso = new Date(nowMs).toISOString();
154
+ currentAssignment.lastRefreshDeltaMs = delta;
155
+ return delta;
156
+ }