async function ensurePrimaryMiddleware (req, res, next) {
  const start = Date.now()
  let logPrefix = '[ensurePrimaryMiddleware]'
  const logger = req.logger

  const serviceRegistry = req.app.get('serviceRegistry')
  const { nodeConfig, libs } = serviceRegistry

  if (!req.session || !req.session.wallet) {
    return sendResponse(req, res, errorResponseUnauthorized(`${logPrefix} User must be logged in`))
  }

  if (!req.session.userId) {
    return sendResponse(req, res, errorResponseBadRequest(`${logPrefix} User must specify 'User-Id' request header`))
  }
  const userId = req.session.userId

  logPrefix = `${logPrefix} [userId = ${userId}]`

  const selfSpID = nodeConfig.get('spID')
  if (!selfSpID) {
    return sendResponse(req, res, errorResponseServerError(`${logPrefix} Node failed to recover its own spID. Cannot validate user write.`))
  }

  /**
   * Fetch current user replicaSetSpIDs
   * Will throw error if selfSpID is not user primary
   */
  let replicaSetSpIDs
  try {
    replicaSetSpIDs = await getReplicaSetSpIDs({
      serviceRegistry,
      logger: req.logger,
      blockNumber: req.body.blockNumber,
      ensurePrimary: true,
      selfSpID,
      userId
    })
  } catch (e) {
    return sendResponse(req, res, errorResponseServerError(`${logPrefix} ${e.message}`))
  }

  const primarySpID = replicaSetSpIDs[0]

  // TODO there should be no need to do this validation (standardize / cleanup errors between here and in getReplicaSetSpIDs())
  if (selfSpID !== primarySpID) {
    return sendResponse(req, res, errorResponseUnauthorized(`${logPrefix} Failed. This node's spID (${selfSpID}) does not match user's primary spID on chain (${primarySpID}).`))
  }

  req.session.replicaSetSpIDs = replicaSetSpIDs
  req.session.nodeIsPrimary = true

  /**
   * Convert replicaSetSpIDs to replicaSetEndpoints for later consumption (do not error on failure)
   * Currently `req.session.creatorNodeEndpoints` is only used by `issueAndWaitForSecondarySyncRequests()`
   * There is a possibility of failing to retrieve endpoints for each spID, so the consumer of req.session.creatorNodeEndpoints must perform null checks
   */
  const allRegisteredCNodes = await utils.getAllRegisteredCNodes(libs, logger)
  const replicaSetEndpoints = replicaSetSpIDs.map(replicaSpID => {
    if (replicaSpID === selfSpID) {
      return nodeConfig.get('creatorNodeEndpoint')
    }
    // Get endpoint from registeredCNode matching current replicaSpID
    const replicaSetInfo = (allRegisteredCNodes.filter(CNodeInfo => CNodeInfo.spID === replicaSpID))[0]
    if (replicaSetInfo && replicaSetInfo.endpoint) {
      return replicaSetInfo.endpoint
    }
  })
  req.session.creatorNodeEndpoints = replicaSetEndpoints.filter(Boolean)

  req.logger.info(`${logPrefix} succeeded ${Date.now() - start} ms. creatorNodeEndpoints: ${req.session.creatorNodeEndpoints}`)
  next()
}
/**
 * Blocks writes if node is not the primary for audiusUser associated with wallet
 */
Blocks writes if node is not the primary for audiusUser associated with wallet
Blocks writes if node is not the primary for audiusUser associated with wallet
async function ensurePrimaryMiddleware (req, res, next) {
  const start = Date.now()
  let logPrefix = '[ensurePrimaryMiddleware]'
  const logger = req.logger
  const serviceRegistry = req.app.get('serviceRegistry')
  const { nodeConfig, libs } = serviceRegistry
  if (!req.session || !req.session.wallet) {
    return sendResponse(req, res, errorResponseUnauthorized(`${logPrefix} User must be logged in`))
  }
  if (!req.session.userId) {
    return sendResponse(req, res, errorResponseBadRequest(`${logPrefix} User must specify 'User-Id' request header`))
  }
  const userId = req.session.userId
  logPrefix = `${logPrefix} [userId = ${userId}]`
  const selfSpID = nodeConfig.get('spID')
  if (!selfSpID) {
    return sendResponse(req, res, errorResponseServerError(`${logPrefix} Node failed to recover its own spID. Cannot validate user write.`))
  }
  let replicaSetSpIDs
  try {
    replicaSetSpIDs = await getReplicaSetSpIDs({
      serviceRegistry,
      logger: req.logger,
      blockNumber: req.body.blockNumber,
      ensurePrimary: true,
      selfSpID,
      userId
    })
  } catch (e) {
    return sendResponse(req, res, errorResponseServerError(`${logPrefix} ${e.message}`))
  }
  const primarySpID = replicaSetSpIDs[0]
  if (selfSpID !== primarySpID) {
    return sendResponse(req, res, errorResponseUnauthorized(`${logPrefix} Failed. This node's spID (${selfSpID}) does not match user's primary spID on chain (${primarySpID}).`))
  }
  req.session.replicaSetSpIDs = replicaSetSpIDs
  req.session.nodeIsPrimary = true
  const allRegisteredCNodes = await utils.getAllRegisteredCNodes(libs, logger)
  const replicaSetEndpoints = replicaSetSpIDs.map(replicaSpID => {
    if (replicaSpID === selfSpID) {
      return nodeConfig.get('creatorNodeEndpoint')
    }
    const replicaSetInfo = (allRegisteredCNodes.filter(CNodeInfo => CNodeInfo.spID === replicaSpID))[0]
    if (replicaSetInfo && replicaSetInfo.endpoint) {
      return replicaSetInfo.endpoint
    }
  })
  req.session.creatorNodeEndpoints = replicaSetEndpoints.filter(Boolean)
  req.logger.info(`${logPrefix} succeeded ${Date.now() - start} ms. creatorNodeEndpoints: ${req.session.creatorNodeEndpoints}`)
  next()
}
async function ensurePrimaryMiddleware ( req , res , next ) { const start = Date . now ( ) let logPrefix = '[ensurePrimaryMiddleware]' const logger = req . logger const serviceRegistry = req . app . get ( 'serviceRegistry' ) const { nodeConfig , libs } = serviceRegistry if ( ! req . session || ! req . session . wallet ) { return sendResponse ( req , res , errorResponseUnauthorized ( ` ${ logPrefix } ` ) ) } if ( ! req . session . userId ) { return sendResponse ( req , res , errorResponseBadRequest ( ` ${ logPrefix } ` ) ) } const userId = req . session . userId logPrefix = ` ${ logPrefix } ${ userId } ` const selfSpID = nodeConfig . get ( 'spID' ) if ( ! selfSpID ) { return sendResponse ( req , res , errorResponseServerError ( ` ${ logPrefix } ` ) ) } let replicaSetSpIDs try { replicaSetSpIDs = await getReplicaSetSpIDs ( { serviceRegistry , logger : req . logger , blockNumber : req . body . blockNumber , ensurePrimary : true , selfSpID , userId } ) } catch ( e ) { return sendResponse ( req , res , errorResponseServerError ( ` ${ logPrefix } ${ e . message } ` ) ) } const primarySpID = replicaSetSpIDs [ 0 ] if ( selfSpID !== primarySpID ) { return sendResponse ( req , res , errorResponseUnauthorized ( ` ${ logPrefix } ${ selfSpID } ${ primarySpID } ` ) ) } req . session . replicaSetSpIDs = replicaSetSpIDs req . session . nodeIsPrimary = true const allRegisteredCNodes = await utils . getAllRegisteredCNodes ( libs , logger ) const replicaSetEndpoints = replicaSetSpIDs . map ( replicaSpID => { if ( replicaSpID === selfSpID ) { return nodeConfig . get ( 'creatorNodeEndpoint' ) } const replicaSetInfo = ( allRegisteredCNodes . filter ( CNodeInfo => CNodeInfo . spID === replicaSpID ) ) [ 0 ] if ( replicaSetInfo && replicaSetInfo . endpoint ) { return replicaSetInfo . endpoint } } ) req . session . creatorNodeEndpoints = replicaSetEndpoints . filter ( Boolean ) req . logger . info ( ` ${ logPrefix } ${ Date . now ( ) - start } ${ req . session . creatorNodeEndpoints } ` ) next ( ) }
Blocks writes if node is not the primary for audiusUser associated with wallet
Blocks writes if node is not the primary for audiusUser associated with wallet
/**
   * Fetch current user replicaSetSpIDs
   * Will throw error if selfSpID is not user primary
   */ // TODO there should be no need to do this validation (standardize / cleanup errors between here and in getReplicaSetSpIDs()) /**
   * Convert replicaSetSpIDs to replicaSetEndpoints for later consumption (do not error on failure)
   * Currently `req.session.creatorNodeEndpoints` is only used by `issueAndWaitForSecondarySyncRequests()`
   * There is a possibility of failing to retrieve endpoints for each spID, so the consumer of req.session.creatorNodeEndpoints must perform null checks
   */ // Get endpoint from registeredCNode matching current replicaSpID