/** * @module sync-peer-http-sender-v1 */ import { extractErrorMsg } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs'; import { SyncPeer_V1 } from '../sync-peer-v1.mjs'; import { SyncSagaContextIbGib_V1 } from '../../sync-saga-context/sync-saga-context-types.mjs'; import { IbGibSpaceAny } from '../../../witness/space/space-base-v1.mjs'; import { GLOBAL_LOG_A_LOT } from '../../../core-constants.mjs'; import { InitializeSyncPeerHttpSenderOpts, SyncPeerHttpSenderData_V1, SyncPeerHttpSenderRel8ns_V1, SyncPeerHttpSenderIbGib_V1, ConnectSyncPeerHttpSenderOpts } from './sync-peer-http-sender-types.mjs'; import { KeystoneIbGib_V1 } from '../../../keystone/keystone-types.mjs'; const logalot = GLOBAL_LOG_A_LOT; /** * Http Sender Peer implementation. * Sends Context to a remote server utilizing POST for uplink and SSE for downlink. */ export class SyncPeerHttpSender_V1 extends SyncPeer_V1 implements SyncPeerHttpSenderIbGib_V1 { protected override lc: string = `[${SyncPeerHttpSender_V1.name}]`; override get classname(): string { return SyncPeerHttpSender_V1.name; } declare data: SyncPeerHttpSenderData_V1 | undefined; declare rel8ns: SyncPeerHttpSenderRel8ns_V1 | undefined; /** * Stored reference to the SSE EventSource connection. * Ensure you polyfill EventSource in Node environments if needed. */ protected eventSource?: EventSource; constructor( initialData: SyncPeerHttpSenderData_V1, initialRel8ns?: SyncPeerHttpSenderRel8ns_V1, ) { super(initialData, initialRel8ns); } protected override preConnectCheck(opts: ConnectSyncPeerHttpSenderOpts): Promise { const lc = `${this.lc}[${this.preConnectCheck.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 518718d0aa6830e182892b68fe2a2826)`); } throw new Error(`not implemented (E: 248be8a09b4dbd2fa820ef78258c5326)`); } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } protected override async connectImpl(opts: ConnectSyncPeerHttpSenderOpts): Promise { const lc = `${this.lc}[${this.connectImpl.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: ad84d8137351662fb8a30114a1fa4826)`); } throw new Error(`not implemented (E: 50752d5f4d188c45727d293549bffd26)`); // Stub implementation for now. } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } protected override async postEstablishToReceiver({ newSenderIdentity, sessionIdentity, }: { newSenderIdentity: KeystoneIbGib_V1; sessionIdentity: KeystoneIbGib_V1; }): Promise { const lc = `${this.lc}[${this.postEstablishToReceiver.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 13e89858eb48b8ab58b15e75032ac826)`); } throw new Error(`not implemented for HTTP sender peer yet (E: b1c2d3e4f5a67890abcdef1234567890)`); } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } protected override async sendContextRequest(context: SyncSagaContextIbGib_V1): Promise { const lc = `${this.lc}[${this.sendContextRequest.name}]`; try { if (logalot) { console.log(`${lc} starting...`); } if (!this.data?.syncEventsRoute) { throw new Error(`data.syncEventsRoute required. (E: 0338214dcd6fbe80f93a24e8a3df3226)`); } if (!this.data?.syncRoute) { throw new Error(`data.syncRoute required. (E: eda70809feb81c880c6accf83fc38826)`); } // 1. Establish SSE connection to `this.data.syncEventsRoute` if not already open // (In a real implementation, you might initialize this elsewhere or ensure it stays reconnecting) if (!this.eventSource) { if (logalot) { console.log(`${lc} initializing EventSource to ${this.data.syncEventsRoute}`); } this.eventSource = new EventSource(this.data.syncEventsRoute); this.eventSource.onerror = (err) => console.error(`${lc} EventSource error:`, err); } return new Promise(async (resolve, reject) => { // 2. Setup listeners for SSE incoming context and ibgib payloads const onMessage = async (event: MessageEvent) => { try { const parsedData = JSON.parse(event.data); // TODO [USER]: Determine if `parsedData` is a domain payload ibGib OR the final response context. // e.g.: // if (parsedData.isDomainIbGib) { // // Deserialize to IbGib_V1 // const ibGib = parsedData; // await this.payloadIbGibsDomainReceived$.next(ibGib); // } else if (parsedData.isResponseContext) { // // Deserialize to SyncSagaContextIbGib_V1 // const responseContext = parsedData; // this.eventSource?.removeEventListener('message', onMessage); // resolve(responseContext); // } } catch (e) { console.error(`${lc} failed to parse SSE message`, e); } }; this.eventSource!.addEventListener('message', onMessage); try { // 3. Serialize Context and Control IbGibs // TODO [USER]: Serialize the `context` and `controlIbGibs` into your wire format const payloadBody = JSON.stringify({ context: context, // controlIbGibs: ... }); // 4. POST the context to `this.data.syncRoute` if (!this.data) { throw new Error(`(UNEXPECTED) this.data falsy? (E: 8c6aa9e1aa7869465a26ee3a7d136826)`); } const response = await fetch(this.data.syncRoute, { method: 'POST', headers: { 'Content-Type': 'application/json', // Add Authorization headers here if needed }, body: payloadBody, }); if (!response.ok) { throw new Error(`HTTP Sync Error: ${response.status} ${await response.text()} (E: f086e8ae65780182b894f638933ca826)`); } // 5. Wait for the SSE stream response to resolve with the responseContext // The Promise will remain pending until `onMessage` identifies the final response context and calls resolve(). } catch (e) { this.eventSource?.removeEventListener('message', onMessage); reject(e); } }); } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } }