Files
speckle-server/packages/server/modules/core/rest/diffDownload.js
T
Iain Sproat 84cb74e8b3 feat(structured logging): implements structured logging for backend (#1217)
* each log line is a json object
* structured logging allows logs to be ingested by machines and the logs to be indexed and queried addresses #1105
* structured logging allows arbitrary properties to be appended to each log line, and ingestion of logs to remain robust
* Structured logging provided by `pino` library
* Add `express-pino-logger` dependency
* Remove `debug`, `morgan`, and `morgan-debug` and replace with structured logging
* `console.log` & `console.error` replaced with structured logging in backend
* Remove `DEBUG` environment variable and replace with `LOG_LEVEL`
- Note that there is a test which reads from a logged line on `stdout`. This is not robust, it would be better to use the childProcess.pid to look up the port number.
* Log errors at points we explicitly send error to Sentry
* Amend indentation of a couple of log messages to align indentation with others
2022-11-25 16:05:05 +00:00

96 lines
2.9 KiB
JavaScript

'use strict'
const zlib = require('zlib')
const cors = require('cors')
const { contextMiddleware } = require('@/modules/shared')
const { validatePermissionsReadStream } = require('./authUtils')
const { SpeckleObjectsStream } = require('./speckleObjectsStream')
const { getObjectsStream } = require('../services/objects')
const {
rejectsRequestWithRatelimitStatusIfNeeded
} = require('@/modules/core/services/ratelimits')
const { pipeline, PassThrough } = require('stream')
const { logger } = require('@/logging/logging')
module.exports = (app) => {
app.options('/api/getobjects/:streamId', cors())
app.post('/api/getobjects/:streamId', cors(), contextMiddleware, async (req, res) => {
const rejected = await rejectsRequestWithRatelimitStatusIfNeeded({
action: 'POST /api/getobjects/:streamId',
req,
res
})
if (rejected) return rejected
const hasStreamAccess = await validatePermissionsReadStream(
req.params.streamId,
req
)
if (!hasStreamAccess.result) {
return res.status(hasStreamAccess.status).end()
}
const childrenList = JSON.parse(req.body.objects)
const simpleText = req.headers.accept === 'text/plain'
res.writeHead(200, {
'Content-Encoding': 'gzip',
'Content-Type': simpleText ? 'text/plain; charset=UTF-8' : 'application/json'
})
// "output" stream, connected to res with `pipeline` (auto-closing res)
const speckleObjStream = new SpeckleObjectsStream(simpleText)
const gzipStream = zlib.createGzip()
pipeline(
speckleObjStream,
gzipStream,
new PassThrough({ highWaterMark: 16384 * 31 }),
res,
(err) => {
if (err) {
logger.error(
`[User ${
req.context.userId || '-'
}] App error streaming objects from stream ${req.params.streamId}: ${err}`
)
} else {
logger.info(
`[User ${req.context.userId || '-'}] Streamed ${
childrenList.length
} objects from stream ${req.params.streamId} (size: ${
gzipStream.bytesWritten / 1000000
} MB)`
)
}
}
)
const cSize = 1000
try {
for (let cStart = 0; cStart < childrenList.length; cStart += cSize) {
const childrenChunk = childrenList.slice(cStart, cStart + cSize)
const dbStream = await getObjectsStream({
streamId: req.params.streamId,
objectIds: childrenChunk
})
await new Promise((resolve, reject) => {
dbStream.pipe(speckleObjStream, { end: false })
dbStream.once('end', resolve)
dbStream.once('error', reject)
})
}
} catch (ex) {
logger.error(
`[User ${req.context.userId || '-'}] DB Error streaming objects from stream ${
req.params.streamId
}: ${ex}`
)
speckleObjStream.emit('error', new Error('Database streaming error'))
}
speckleObjStream.end()
})
}