1+ import { spawn } from 'child_process' ;
2+ import yaml from 'yaml' ;
3+ import fs from 'fs' ;
4+ import fetch from 'node-fetch' ;
5+
6+ const sleep = ms => new Promise ( r => setTimeout ( r , ms ) ) ;
7+
8+ async function checkReachable ( url ) {
9+ const res = await fetch ( url , {
10+ method : 'POST' ,
11+ headers : { 'Content-Type' : 'application/json' } ,
12+ body : `{ "query": "query {__schema {__typename}}" }` ,
13+ } ) ;
14+ return res . ok ;
15+ }
16+
17+ // get urls of services we need to wait for
18+ const meshRc = fs . readFileSync ( './.meshrc.yaml' , 'utf8' ) ;
19+ const config = yaml . parse ( meshRc ) ;
20+
21+ // replace env variables in urls
22+ const serviceEndpoints = [ ]
23+ const reEnv = / { e n v \. ( .+ ) } / g
24+ for ( const service of config . sources ) {
25+ let url = service . handler . graphql . endpoint ;
26+ if ( url ) {
27+ url = url . replace ( reEnv , ( _ , envVar ) => {
28+ return process . env [ envVar ] || '' ;
29+ } ) ;
30+ serviceEndpoints . push ( {
31+ name : service . name ,
32+ url : url ,
33+ } ) ;
34+ }
35+ }
36+
37+ // wait for urls to be reachable
38+ while ( true ) {
39+ const notReachable = [ ] ;
40+ for ( const service of serviceEndpoints ) {
41+ try {
42+ const reachable = await checkReachable ( service . url ) ;
43+ if ( ! reachable ) {
44+ notReachable . push ( service . name ) ;
45+ }
46+ } catch ( error ) {
47+ console . log ( 'Failed trying to reach service:' , error . message ) ;
48+ notReachable . push ( service . name ) ;
49+ }
50+ }
51+
52+ if ( notReachable . length === 0 ) {
53+ break ;
54+ } else {
55+ console . log ( 'Waiting for services to be reachable:' , notReachable . join ( ', ' ) ) ;
56+ }
57+ console . log ( 'Retrying in 5 seconds...' ) ;
58+ await sleep ( 5000 ) ;
59+ }
60+
61+ console . log ( 'All services are reachable, starting mesh after 2 seconds...' ) ;
62+ await sleep ( 2000 ) ; // additional wait to ensure services are ready
63+
64+ // run mesh
65+ const meshProcess = spawn ( 'npx' , [ 'mesh' , 'dev' ] , {
66+ stdio : 'inherit' ,
67+ shell : true ,
68+ } ) ;
69+
70+ meshProcess . on ( 'close' , ( code ) => {
71+ console . log ( `Mesh process exited with code ${ code } ` ) ;
72+ process . exit ( code ?? 0 ) ;
73+ } ) ;
0 commit comments