Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
const apmSpan = apm.startSpan('Get access info for API key')
accessInfo = await computeAccessInfo({
roles: apiKey.roles,
permissions: apiKey.permissions,
readNamespaces: apiKey.readNamespaces,
editNamespaces: apiKey.editNamespaces,
...computeAccessParams
})
apmSpan && apmSpan.end()
} else if (token && typeof token === 'object') {
sources.push('token')
const apmSpan = apm.startSpan('Get access info for token')
// the header x-stelace-organization-id is only useful for authentication by token
organizationId = req.headers['x-stelace-organization-id']
const tokenPermissions = token.permissions || []
let scopePermissions = []
if (token.scope && typeof token.scope === 'string') {
scopePermissions = token.scope.split(' ')
}
// routes/services can override the `organizationId` (like in user.joinOrganizationOrUpdateRights)
if (typeof getOrganizationIdFn === 'function') {
organizationId = getOrganizationIdFn(req)
}
const apmNode = require('elastic-apm-node');
const env = require('../env');
console.log('Starting server side APM.');
const apm = apmNode.start({
serviceName: 'wheelmap-react-frontend',
serviceVersion: env.npm_package_version, // Used on the APM Server to find the right sourcemap
serverUrl: env.ELASTIC_APM_SERVER_URL,
secretToken: env.ELASTIC_APM_SECRET_TOKEN,
});
module.exports = apm;
async applyChanges ({ target, fromVersion, toVersion, params = {} }) {
const apmSpan = apm.startSpan(`${this.label} version transformation`)
let transformedParams = params
// apply the change for ANY version and ANY target
// and before all other changes
const beforeAllChange = this.getChange({ version: 'always', target: 'beforeAll' })
if (_.isPlainObject(beforeAllChange)) {
transformedParams = await beforeAllChange[this.direction](transformedParams)
}
const index = this.apiVersions.indexOf(fromVersion)
const foundVersion = index !== -1
if (foundVersion) {
for (let i = index; i < this.apiVersions.length; i++) {
const version = this.apiVersions[i]
async send (...args) {
const sendParams = args[0] || {}
const name = `Requester send: ${this.advertisement.name} | type: ${sendParams.type}`
const apmSpan = apm.startSpan(name)
// used to link to the source APM transaction across network (see custom responder)
if (apm.currentTransaction) {
sendParams._apmTraceparent = apm.currentTransaction.traceparent
}
try {
const result = await super.send(...args)
return result
} finally {
if (isApmActive && !apmSpan) {
if (!apm.currentTransaction) {
logError(new Error(`No APM transaction available in requester "${name}"`))
} else {
logError(new Error(`Empty apm span in requester "${name}"`))
}
const middleware = async (req, res, next) => {
const apmSpan = apm.startSpan('Check permissions')
const permissionsToCheck = permissions.slice(0)
// Always check, in case platformData is edited via current endpoint
if (!permissionsToCheck.includes('platformData:edit:all')) {
permissionsToCheck.push('platformData:edit:all')
}
optionalPermissions.forEach(p => permissionsToCheck.push(p))
try {
const token = req[requestProperty]
const rawApiKey = _.get(req.authorization, 'apiKey') ||
req.headers['x-api-key'] // legacy x-api-key, convenient during development
const stelaceWorkflowKey = req.headers['x-stelace-workflow-key']
const targetUserId = req.headers['x-stelace-user-id']
server.use((req, res, next) => {
req.apmSpans.restifyPlugin && req.apmSpans.restifyPlugins.end()
req.apmSpans.restifyPlugins = null
req.apmSpans.requestInit = apm.startSpan('Request initialization')
req._requestId = Uuid.v4()
req._ip = getIp(req)
// set this header for CORS
res.header('access-control-allow-credentials', true)
next()
})
server.use(async (req, res, next) => {
const apmSpan = apm.startSpan('Parse Authorization and get platform info')
try {
parseAuthorizationHeader(req)
} catch (err) { // still trying to parse authorization header for convenience when not required
if (!req._manualAuthRoute) {
apmSpan && apmSpan.end()
return next(err)
}
}
try {
const setPlanAndVersion = async ({ errParams } = {}) => {
try {
const info = await getPlatformEnvData(req.platformId, req.env, [
'plan', // can be set by some plugin
'version'
// istanbul ignore next
if (require.main === module) {
// This needs to run before any require() call.
global.apmClient = require('elastic-apm-node').start({});
global.apmClient.addTransactionFilter(payload => (payload.context && payload.context.tags && payload.context.tags.userAgent && !payload.context.tags.userAgent.includes('sindresorhus/got')) || Math.random() < .2 ? payload : false);
global.apmClient.addTransactionFilter(require('elastic-apm-utils').apm.transactionFilter());
global.apmClient.addSpanFilter(require('elastic-apm-utils').apm.spanFilter({ filterShorterThan: 10 }));
require('./lib/startup');
}
const config = require('config');
const signalExit = require('signal-exit');
const Koa = require('koa');
const koaFavicon = require('koa-favicon');
const koaResponseTime = require('koa-response-time');
const koaConditionalGet = require('koa-conditional-get');
const koaCompress = require('koa-compress');
const koaLogger = require('koa-logger');
const koaETag = require('koa-etag');
const koaJson = require('koa-json');
eventSubscriber.on('eventCreated', async ({ event, platformId, env } = {}) => {
// APM transaction needs to be created for customRequester
// Note: APM transactions cannot be nested
const prepareWorkflowsTransaction = apm.startTransaction('Prepare Workflows', 'workflow')
apm.setUserContext({ id: platformId })
apm.addLabels({ platformId, env, eventType: event.type })
/*
Objects to be shared across ALL workflows for this single event
Remember that these can be mutated/overwritten by each of them
*/
let runId
let workflowsCtx = {} // shared and same for all current event’s workflows
let vm
try {
const {
Event,
Workflow,
WorkflowLog
async function emitTaskEvents () {
let fetchEventsTransaction = apm.startTransaction('Fetch task events to emit via cron')
try {
// use ref date because cron job cannot trigger at the specified time (with 0 millisecond)
const refDate = getRoundedDate(new Date(), nbMinutes)
const taskConfigs = await getAllStelaceTasks()
const filteredTaskConfigs = filterTasks(taskConfigs, refDate, nbMinutes)
fetchEventsTransaction.end()
fetchEventsTransaction = null // set null to prevent stopping a second time in the finally block
for (let i = 0; i < filteredTaskConfigs.length; i++) {
const taskConfig = filteredTaskConfigs[i]
const { platformId, env, task } = taskConfig