update
This commit is contained in:
+56
-43
@@ -21,8 +21,13 @@ let reconnectTimer = null;
|
||||
let isDisconnecting = false;
|
||||
|
||||
export async function getNats(opts = {}) {
|
||||
const servers = opts.servers || (import.meta.env.VITE_NATS_URL) || (config?.nats_server_info?.url) || "wss://nats.yiem.cc";
|
||||
const servers = opts.servers || (import.meta.env.VITE_NATS_URL) || (config?.nats_server_info?.url) || "wss://natsws.yiem.cc";
|
||||
console.log('[NATS] Connecting to:', servers);
|
||||
|
||||
clearTimeout(reconnectTimer);
|
||||
reconnectTimer = null;
|
||||
isDisconnecting = false;
|
||||
|
||||
try {
|
||||
connectionStatus.set({ state: "connecting", message: `connecting to ${servers}` });
|
||||
console.log('[NATS] Status: connecting');
|
||||
@@ -31,57 +36,43 @@ export async function getNats(opts = {}) {
|
||||
connectionStatus.set({ state: "connected", message: `connected to ${servers}` });
|
||||
isDisconnecting = false;
|
||||
|
||||
// Track connection state changes for status dot
|
||||
// nats.ws emits status events for disconnect/reconnect
|
||||
const statusSub = nc.status();
|
||||
(async () => {
|
||||
for await (const status of statusSub) {
|
||||
console.log('[NATS] Status event:', status.type, status.data);
|
||||
if (status.type === 'disconnect') {
|
||||
connectionStatus.set({ state: 'disconnected', message: 'connection lost' });
|
||||
} else if (status.type === 'reconnect') {
|
||||
connectionStatus.set({ state: 'connected', message: 'reconnected' });
|
||||
} else if (status.type === 'connect') {
|
||||
connectionStatus.set({ state: 'connected', message: `connected to ${servers}` });
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
// Also monitor permanent closure
|
||||
nc.closed().then((err) => {
|
||||
if (isDisconnecting) return;
|
||||
if (err) {
|
||||
console.log('[NATS] Connection closed with error:', err);
|
||||
console.log('[NATS] Connection permanently closed with error:', err);
|
||||
connectionStatus.set({ state: "error", message: String(err) });
|
||||
} else {
|
||||
console.log('[NATS] Connection closed normally');
|
||||
console.log('[NATS] Connection permanently closed normally');
|
||||
connectionStatus.set({ state: "disconnected", message: "connection closed" });
|
||||
}
|
||||
attemptReconnect(servers);
|
||||
});
|
||||
|
||||
return nc;
|
||||
} catch (e) {
|
||||
console.error('[NATS] Connection failed:', e);
|
||||
connectionStatus.set({ state: "error", message: String(e) });
|
||||
attemptReconnect(servers);
|
||||
// nats.ws will automatically attempt reconnect when we call getNats() again
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
async function attemptReconnect(servers, retryCount = 0) {
|
||||
const maxDelay = 30000;
|
||||
const baseDelay = Math.min(1000 * Math.pow(2, retryCount), maxDelay);
|
||||
|
||||
console.log(`[NATS] Reconnecting in ${baseDelay}ms (attempt ${retryCount + 1})...`);
|
||||
|
||||
reconnectTimer = setTimeout(async () => {
|
||||
try {
|
||||
connectionStatus.set({ state: "connecting", message: `reconnecting to ${servers}` });
|
||||
nc = await connect({ servers });
|
||||
console.log('[NATS] Reconnected successfully!');
|
||||
connectionStatus.set({ state: "connected", message: `connected to ${servers}` });
|
||||
isDisconnecting = false;
|
||||
|
||||
const subsCopy = Array.from(subs.entries());
|
||||
for (const [subject, onMessage] of subsCopy) {
|
||||
try {
|
||||
await subscribe(subject, onMessage);
|
||||
} catch (e) {
|
||||
console.warn(`[NATS] Failed to re-subscribe to ${subject}:`, e);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('[NATS] Reconnection failed:', e);
|
||||
connectionStatus.set({ state: "error", message: String(e) });
|
||||
attemptReconnect(servers, retryCount + 1);
|
||||
}
|
||||
}, baseDelay);
|
||||
}
|
||||
|
||||
export async function subscribe(subject, onMessage) {
|
||||
console.log('[NATS] Subscribing to:', subject);
|
||||
if (!nc) await getNats();
|
||||
@@ -112,15 +103,27 @@ export async function subscribe(subject, onMessage) {
|
||||
}
|
||||
|
||||
export async function publish(subject, payload = {}, opts = {}) {
|
||||
console.log('[NATS] Publishing to:', subject, 'payload:', payload);
|
||||
if (!nc) await getNats(opts);
|
||||
console.log('[NATS] Publishing to subject:', subject);
|
||||
console.log('[NATS] Payload type:', typeof payload);
|
||||
console.log('[NATS] Payload (as JSON):', typeof payload === 'string' ? payload : JSON.stringify(payload, null, 2));
|
||||
if (!nc) {
|
||||
console.log('[NATS] No connection, attempting to connect...');
|
||||
await getNats(opts);
|
||||
}
|
||||
const msg = typeof payload === "string" ? payload : JSON.stringify(payload);
|
||||
console.log('[NATS] Final message to publish (first 300 chars):', msg.substring(0, 300) + (msg.length > 300 ? '...' : ''));
|
||||
console.log('[NATS] Message length:', msg.length);
|
||||
console.log('[NATS] NATS connection exists:', !!nc);
|
||||
console.log('[NATS] About to publish...');
|
||||
nc.publish(subject, sc.encode(msg));
|
||||
console.log('[NATS] Message published successfully');
|
||||
console.log('[NATS] Message published successfully to:', subject);
|
||||
}
|
||||
|
||||
export async function closeNats() {
|
||||
console.log('[NATS] Closing connection...');
|
||||
clearTimeout(reconnectTimer);
|
||||
reconnectTimer = null;
|
||||
isDisconnecting = true;
|
||||
connectionStatus.set({ state: "disconnected", message: "closing" });
|
||||
try {
|
||||
for (const s of subs.values()) {
|
||||
@@ -145,7 +148,7 @@ export async function connectNATS(brokerUrl, cfg) {
|
||||
let serverUrl = brokerUrl;
|
||||
|
||||
if (!serverUrl && cfg) {
|
||||
serverUrl = cfg?.nats_server_info?.url || 'wss://nats.yiem.cc';
|
||||
serverUrl = cfg?.nats_server_info?.url || 'wss://natsws.yiem.cc';
|
||||
}
|
||||
|
||||
console.log('[NATS] Using server URL:', serverUrl);
|
||||
@@ -155,10 +158,12 @@ export async function connectNATS(brokerUrl, cfg) {
|
||||
|
||||
export async function request(subject, payload, opts = {}) {
|
||||
console.log('[NATS] Requesting from:', subject, 'payload:', payload);
|
||||
if (!nc) await getNats(opts);
|
||||
const { timeout, ...getNatsOpts } = opts;
|
||||
if (!nc) await getNats(getNatsOpts);
|
||||
|
||||
const msg = typeof payload === "string" ? payload : JSON.stringify(payload);
|
||||
const response = await nc.request(subject, sc.encode(msg));
|
||||
const requestOpts = timeout ? { timeout } : {};
|
||||
const response = await nc.request(subject, sc.encode(msg), requestOpts);
|
||||
const responseText = sc.decode(response.data);
|
||||
let responseJson;
|
||||
try {
|
||||
@@ -213,8 +218,8 @@ export async function sendMsghandlerRequest(subject, functioncall, args, config)
|
||||
args: args
|
||||
};
|
||||
|
||||
const brokerUrl = config?.nats_server_info?.url || 'wss://nats.yiem.cc';
|
||||
const fileserverUrl = config?.file_server_url || 'http://localhost:8080';
|
||||
const brokerUrl = config?.nats_server_info?.url || 'wss://natsws.yiem.cc';
|
||||
const fileserverUrl = config?.file_server_url || 'https://fileserver.yiem.cc';
|
||||
|
||||
const [envelope, envelopeJsonStr] = await msghandlerCSR.smartpack(
|
||||
subject,
|
||||
@@ -236,3 +241,11 @@ export async function sendMsghandlerRequest(subject, functioncall, args, config)
|
||||
console.log('[NATS] Request successful:', data);
|
||||
return data;
|
||||
}
|
||||
if (type === "text") {
|
||||
console.error('[NATS] Error response:', data);
|
||||
throw new Error(data);
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error('No valid response found');
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user