2022-01-23 19:51:23 +00:00
"use strict" ;
import Agent from './agent/Agent.mjs' ;
2022-01-30 00:51:28 +00:00
import InfoBroker from './core/InfoBroker.mjs' ;
2022-01-23 19:51:23 +00:00
class SystemQuery {
2022-01-31 03:06:34 +00:00
constructor ( config , mode = "agent" ) {
// The operating mode. Possible values: agent [default], query_client
// TODO: Is this the best way of doing this? Maybe we should have a separate class for this? I'm not sure.
this . mode = mode ;
2022-01-23 19:51:23 +00:00
this . config = config ;
2022-01-30 00:51:28 +00:00
this . info = new InfoBroker ( ) ;
2022-01-23 19:51:23 +00:00
}
async init ( ) {
///
// 1: Create agent
///
this . agent = new Agent ( this . config ) ;
await this . agent . init ( ) ;
///
// 2: Attach listeners
///
this . agent . on ( "message-query" , this . handle _query . bind ( this ) ) ;
this . agent . on ( "message-query-response" , this . handle _query _response . bind ( this ) ) ;
}
async handle _query ( peer , msg ) {
2022-01-30 00:51:28 +00:00
// 1: Validate input
if ( typeof msg . table !== "string"
|| ! this . info . is _valid _table ( msg . table ) ) return ;
2022-01-23 19:51:23 +00:00
2022-01-30 00:51:28 +00:00
// 2: Fetch system info
let table = await this . info . fetch _table ( msg . table ) ;
if ( table === null ) return ;
// 3: Return to requester
await peer . send ( "query-response" , { result : table } ) ;
2022-01-23 19:51:23 +00:00
}
async handle _query _response ( peer , msg ) {
}
2022-01-31 03:06:34 +00:00
async fetch _table ( name ) {
// If it isn't valid for us, it ain't gonna be valid for anyone else....
if ( ! this . info . is _valid _table ( name ) ) return null ;
const responses = { } ; // peer id → table
const handle _response = async ( peer , msg ) => {
// TODO: Validate response. Is it the right table? Is it even a table? Note that multiple fetch_table calls may be running in parallel, so we should not make too much of a fuss if we get the wrong table by accident.
// TODO: It would be seriously cool to have fetch_table() be an async generator that yields pairs of peer ids and tables as they come in.
if ( no _peers _left _or _hit _timeout ) {
this . off ( "message-query-response" , handle _response ) ;
}
} ;
this . on ( "message-query-response" , handle _response ) ;
// FUTURE: Add a cache here? Note that we also do not listen for query responses unless we've asked for a table.
}
2022-01-23 19:51:23 +00:00
}
SystemQuery . Create = async function ( config ) {
let result = new SystemQuery ( config ) ;
await result . init ( ) ;
return result ;
}
export default SystemQuery ;