fix: couldn't properly start without config file

Massimo Melina committed Feb 9, 2022 at 10:50 UTC 0c44ffe5472e689f5da3fd878d1c605ee5921018
2 files changed +19 -19
src/config.ts
+10 -7
@@ -10,17 +10,19 @@ export const CFG_ALLOW_CLEAR_TEXT_LOGIN = 'allow_clear_text_login'
10
11 const PATH = 'config.yaml'
12
13 +const configProps:Record<string, ConfigProps<any>> = {}
14 +
15 let started = false // this will tell the difference for subscribeConfig()s that are called before or after config is loaded
14 -let state:Record<string,any> = {}
16 +let state: Record<string, any> = {}
17 const emitter = new EventEmitter()
18 emitter.setMaxListeners(10_000)
19 const path = argv.config || process.env.HFS_CONFIG || PATH
18 -watchLoad(path, data => {
19 - started = true
20 - setConfig(data)
21 -}, { failOnFirstAttempt:()=> setConfig({}) })
22 -
23 -const configProps:Record<string, ConfigProps<any>> = {}
20 +watchLoad(path, setConfig, {
21 + failedOnFirstAttempt(){
22 + console.log("No config file, using defaults")
23 + setConfig({})
24 + }
25 +})
26
27 interface ConfigProps<T> {
28 defaultValue?: T,
@@ -64,6 +66,7 @@ export function getWholeConfig({ omit=[], only=[] }: { omit:string[], only:strin
66 }
67
68 export function setConfig(newCfg: Record<string,any>, partial=false) {
69 + started = true
70 for (const k in newCfg)
71 check(k)
72 const oldKeys = Object.keys(state)
src/watchLoad.ts
+9 -12
@@ -5,28 +5,28 @@ import { readFileBusy } from './misc'
5
6 export type WatchLoadCanceller = () => void
7
8 -interface Options { failOnFirstAttempt?: ()=>void }
8 +interface Options { failedOnFirstAttempt?: ()=>void }
9
10 -export function watchLoad(path:string, parser:(data:any)=>void|Promise<void>, { failOnFirstAttempt }:Options={}): WatchLoadCanceller {
10 +export function watchLoad(path:string, parser:(data:any)=>void|Promise<void>, { failedOnFirstAttempt }:Options={}): WatchLoadCanceller {
11 let doing = false
12 - let watcher: FSWatcher
12 + let watcher: FSWatcher | undefined
13 const debounced = _.debounce(load, 500)
14 - let initDone = false
14 + let retry: NodeJS.Timeout
15 init()
16 + if (!watcher)
17 + failedOnFirstAttempt?.()
18 return () => {
17 - initDone = true // stop trying
19 watcher?.close()
20 + clearTimeout(retry)
21 }
22
23 function init() {
24 try {
23 - debounced()
25 watcher = watch(path, debounced)
25 - initDone = true
26 + debounced() // if file is not accessible watch will throw and we won't get here
27 }
28 catch {
28 - if (initDone)
29 - setTimeout(init, 1000)
29 + retry = setTimeout(init, 1000) // manual watching until watch is successful
30 }
31 }
32
@@ -40,10 +40,7 @@ export function watchLoad(path:string, parser:(data:any)=>void|Promise<void>, {
40 if (path.endsWith('.yaml'))
41 data = yaml.parse(data)
42 } catch (e) {
43 - if (!initDone)
44 - failOnFirstAttempt?.()
43 doing = false
46 - console.debug('cannot read', path, String(e))
44 return
45 }
46 await parser(data)