Better logging from subprocess, now uses winston

This commit is contained in:
Daniel Lugo 2021-09-15 12:14:59 -04:00
parent 64d3c8f969
commit dc78fa0371
3 changed files with 71 additions and 26 deletions

View file

@ -133,17 +133,24 @@ let lastPass = ''
let lastPair = null let lastPair = null
/** @type {import('gun/types/options').IGunConstructorOptions} */ /** @type {import('gun/types/options').IGunConstructorOptions} */
let lastOpts = {} let lastOpts = {}
let isAuthing = false
/** /**
* @param {string} alias * @param {string} alias
* @param {string} pass * @param {string} pass
* @returns {Promise<GunT.UserPair>} * @returns {Promise<GunT.UserPair>}
*/ */
const auth = (alias, pass) => const auth = (alias, pass) => {
new Promise((res, rej) => { logger.info(`Authing with ${alias}`)
if (isAuthing) {
throw new Error(`Double auth?`)
}
isAuthing = true
return new Promise((res, rej) => {
lastAlias = '' lastAlias = ''
lastPass = '' lastPass = ''
lastPair = null lastPair = null
logger.info('Reset cached credentials in case auth fails')
/** @type {Smith.SmithMsgAuth} */ /** @type {Smith.SmithMsgAuth} */
const msg = { const msg = {
alias, alias,
@ -154,8 +161,11 @@ const auth = (alias, pass) =>
/** @param {Smith.GunMsg} msg */ /** @param {Smith.GunMsg} msg */
const _cb = msg => { const _cb = msg => {
if (msg.type === 'auth') { if (msg.type === 'auth') {
logger.info('Received auth reply.', msg)
currentGun.off('message', _cb) currentGun.off('message', _cb)
isAuthing = false
const { ack } = msg const { ack } = msg
if (ack.err) { if (ack.err) {
@ -164,6 +174,9 @@ const auth = (alias, pass) =>
lastAlias = alias lastAlias = alias
lastPass = pass lastPass = pass
lastPair = ack.sea lastPair = ack.sea
logger.info(
'Auth successful, credentials cached, will now flush pending puts.'
)
flushPendingPuts() flushPendingPuts()
res(ack.sea) res(ack.sea)
} else { } else {
@ -173,7 +186,9 @@ const auth = (alias, pass) =>
} }
currentGun.on('message', _cb) currentGun.on('message', _cb)
currentGun.send(msg) currentGun.send(msg)
logger.info('Sent auth message.')
}) })
}
/** /**
* Returns null if there's no cached credentials. * Returns null if there's no cached credentials.
@ -181,8 +196,10 @@ const auth = (alias, pass) =>
*/ */
const autoAuth = () => { const autoAuth = () => {
if (!lastAlias || !lastPass) { if (!lastAlias || !lastPass) {
logger.info('No credentials cached, will not auto-auth')
return Promise.resolve(null) return Promise.resolve(null)
} }
logger.info('Credentials cached, will auth.')
return auth(lastAlias, lastPass) return auth(lastAlias, lastPass)
} }
@ -207,30 +224,41 @@ const flushPendingPuts = () => {
return msg return msg
}) })
currentGun.send(messages) currentGun.send(messages)
logger.info(`Sent ${messages.length} pending puts.`)
} }
let isReforging = false
const forge = () => { const forge = () => {
if (isReforging) {
throw new Error('Double forge?')
}
logger.info('Will reforge')
isReforging = true
if (currentGun) { if (currentGun) {
currentGun.off('message', handleMsg) currentGun.off('message', handleMsg)
currentGun.disconnect() currentGun.disconnect()
currentGun.kill() currentGun.kill()
} }
logger.info('Killed current gun')
const newGun = fork('utils/GunSmith/gun.js') const newGun = fork('utils/GunSmith/gun.js')
currentGun = newGun currentGun = newGun
logger.info('Forged new gun')
// currentGun.on('', e => { // currentGun.on('', e => {
// console.log('event from subprocess') // console.log('event from subprocess')
// console.log(e) // console.log(e)
// }) // })
currentGun.on('message', handleMsg)
/** @type {Smith.SmithMsgInit} */ /** @type {Smith.SmithMsgInit} */
const initMsg = { const initMsg = {
opts: lastOpts, opts: lastOpts,
type: 'init' type: 'init'
} }
currentGun.send(initMsg) currentGun.send(initMsg)
logger.info('Sent init msg')
currentGun.on('message', handleMsg)
const lastGunListeners = Object.keys(pathToListeners).map(path => { const lastGunListeners = Object.keys(pathToListeners).map(path => {
/** @type {Smith.SmithMsgOn} */ /** @type {Smith.SmithMsgOn} */
@ -242,6 +270,21 @@ const forge = () => {
}) })
currentGun.send(lastGunListeners) currentGun.send(lastGunListeners)
const lastGunMapListeners = Object.keys(pathToMapListeners).map(path => {
/** @type {Smith.SmithMsgMapOn} */
const msg = {
path,
type: 'map.on'
}
return msg
})
currentGun.send(lastGunMapListeners)
logger.info('Sent pending map.on listeners')
logger.info('Finished reforging, will now auto-auth')
isReforging = false
autoAuth() autoAuth()
} }
@ -398,7 +441,9 @@ function createReplica(path, afterMap = false) {
path, path,
type: 'put' type: 'put'
} }
currentGun.send(msg) if (!isAuthing && !isReforging) {
currentGun.send(msg)
}
return this return this
}, },
set(data, cb) { set(data, cb) {
@ -570,7 +615,7 @@ function createUserReplica() {
} }
/** /**
* @typedef {GunT.GUNNode & { kill(): void }} RootNode * @typedef {GunT.GUNNode & { reforge(): void }} RootNode
*/ */
/** /**
@ -585,12 +630,8 @@ const Gun = opts => {
// signature // signature
return { return {
...createReplica('$root'), ...createReplica('$root'),
kill() { reforge() {
if (currentGun) { forge()
currentGun.off('message', handleMsg)
currentGun.disconnect()
currentGun.kill()
}
} }
} }
} }

View file

@ -35,7 +35,7 @@ describe('constructor', () => {
// eslint-disable-next-line jest/no-hooks // eslint-disable-next-line jest/no-hooks
afterAll(() => { afterAll(() => {
if (instance) { if (instance) {
instance.kill() instance.reforge()
} }
}) })

View file

@ -8,8 +8,7 @@ const Gun = require('gun')
require('gun/nts') require('gun/nts')
require('gun/lib/load') require('gun/lib/load')
// @ts-ignore const logger = require('../../config/log')
Gun.log = () => {}
/** /**
* @param {any} msg * @param {any} msg
@ -18,22 +17,22 @@ const sendMsg = msg => {
if (process.send) { if (process.send) {
process.send(msg) process.send(msg)
} else { } else {
console.log( logger.error(
'Fatal error: Could not send a message from inside the gun process.' 'Fatal error: Could not send a message from inside the gun process.'
) )
} }
} }
console.log('subprocess invoked') logger.info('subprocess invoked')
process.on('uncaughtException', e => { process.on('uncaughtException', e => {
console.log('Uncaught exception inside Gun subprocess:') logger.error('Uncaught exception inside Gun subprocess:')
console.log(e) logger.error(e)
}) })
process.on('unhandledRejection', e => { process.on('unhandledRejection', e => {
console.log('Unhandled rejection inside Gun subprocess:') logger.error('Unhandled rejection inside Gun subprocess:')
console.log(e) logger.error(e)
}) })
/** /**
@ -64,7 +63,7 @@ const waitForAuth = async () => {
/** /**
* @param {Smith.SmithMsg} msg * @param {Smith.SmithMsg} msg
*/ */
const handleMsg = msg => { const handleMsg = async msg => {
if (Array.isArray(msg)) { if (Array.isArray(msg)) {
msg.forEach(handleMsg) msg.forEach(handleMsg)
return return
@ -72,18 +71,23 @@ const handleMsg = msg => {
if (msg.type === 'init') { if (msg.type === 'init') {
gun = /** @type {any} */ (new Gun(msg.opts)) gun = /** @type {any} */ (new Gun(msg.opts))
let lastPeers = '' let currentPeers = ''
setInterval(() => { setInterval(() => {
const newPeers = JSON.stringify( const newPeers = JSON.stringify(
Object.values(gun.back('opt').peers) Object.values(gun.back('opt').peers)
.filter(p => p.wire && p.wire.readyState) .filter(p => p.wire && p.wire.readyState)
.map(p => p.url) .map(p => p.url)
) )
if (newPeers !== lastPeers) { if (newPeers !== currentPeers) {
console.log('Connected peers:', newPeers) logger.info('Connected peers:', newPeers)
lastPeers = newPeers currentPeers = newPeers
} }
}, 2000) }, 2000)
setInterval(() => {
// Log regardless of change every 30 seconds
logger.info('Connected peers:', currentPeers)
}, 30000)
user = gun.user() user = gun.user()
} }
if (msg.type === 'auth') { if (msg.type === 'auth') {