googleapis / google-cloud-node

Google Cloud Client Library for Node.js
https://cloud.google.com/nodejs
Apache License 2.0
2.87k stars 584 forks source link

Error "3 INVALID_ARGUMENT: Invalid resource field value in the request." when awaiting long-running operation #4488

Open skymakerolof opened 11 months ago

skymakerolof commented 11 months ago

When programmatically creating a cloud function, I get the error "3 INVALID_ARGUMENT: Invalid resource field value in the request." when awaiting the long-running operation using the provided promise() call as described in the sample code. I can see that the cloud function is actually created correctly in the Google Cloud Console, so the problem appears to only relate to checking the status of the operation.

Environment details

Steps to reproduce

Create a file debug.js with the content below. Make sure to update the variables projectId, location and keyFilePath with valid values. Add required dependencies with npm install @google-cloud/functions got jszip.

const { CloudFunctionsServiceClient } = require('@google-cloud/functions')
const got = require('got')
const JSZip = require('jszip')

run()

async function run() {
  const projectId = 'my-project-id'
  const location = 'my-location'
  const keyFilePath = '/path/to/my-key.json'
  const parent = `projects/${projectId}/locations/${location}`

  const client = new CloudFunctionsServiceClient({
    keyFile: keyFilePath,
  })

  const [uploadUrlResponse] = await client.generateUploadUrl({ parent })
  const { uploadUrl } = uploadUrlResponse
  if (!uploadUrl) throw new Error('Failed to create upload URL')

  const zip = new JSZip()

  zip.file(
    'index.js',
    `
module.exports.run = async (req, res) => {
  res.send('Hello World!')
}`.trim(),
  )

  const zipBuffer = await zip.generateAsync({ type: 'nodebuffer' })

  await got.put(uploadUrl, {
    body: zipBuffer,
    headers: {
      // https://cloud.google.com/functions/docs/reference/rest/v1/projects.locations.functions/generateUploadUrl
      'content-type': 'application/zip',
      'x-goog-content-length-range': '0,104857600',
    },
  })

  const [longRunningOperation] = await client.createFunction({
    location: parent,
    function: {
      availableMemoryMb: 1024,
      entryPoint: 'run',
      httpsTrigger: {},
      ingressSettings: 'ALLOW_ALL',
      name: `${parent}/functions/my-debug-function`,
      runtime: 'nodejs14',
      sourceUploadUrl: uploadUrl,
    },
  })

  try {
    const [createdFunction] = await longRunningOperation.promise()

    console.log(createdFunction)
  } catch (error) {
    console.error(error)
  }
}

Execute debug.js with NodeJS:

$ node debug.js 
Error: 3 INVALID_ARGUMENT: Invalid resource field value in the request.
    at callErrorFromStatus (C:\debug\node_modules\@grpc\grpc-js\build\src\call.js:31:19)
    at Object.onReceiveStatus (C:\debug\node_modules\@grpc\grpc-js\build\src\client.js:192:76)
    at Object.onReceiveStatus (C:\debug\node_modules\@grpc\grpc-js\build\src\client-interceptors.js:360:141)
    at Object.onReceiveStatus (C:\debug\node_modules\@grpc\grpc-js\build\src\client-interceptors.js:323:181)
    at C:\debug\node_modules\@grpc\grpc-js\build\src\resolving-call.js:94:78
    at process.processTicksAndRejections (node:internal/process/task_queues:77:11)
for call at
    at ServiceClientImpl.makeUnaryRequest (C:\debug\node_modules\@grpc\grpc-js\build\src\client.js:160:32)
    at ServiceClientImpl.<anonymous> (C:\debug\node_modules\@grpc\grpc-js\build\src\make-client.js:105:19)
    at C:\debug\node_modules\google-gax\build\src\operationsClient.js:95:29
    at C:\debug\node_modules\google-gax\build\src\normalCalls\timeout.js:44:16
    at OngoingCallPromise.call (C:\debug\node_modules\google-gax\build\src\call.js:67:27)
    at NormalApiCaller.call (C:\debug\node_modules\google-gax\build\src\normalCalls\normalApiCaller.js:34:19)
    at C:\debug\node_modules\google-gax\build\src\createApiCall.js:84:30 {
  code: 3,
  details: 'Invalid resource field value in the request.',
  metadata: Metadata {
    internalRepr: Map(4) {
      'endpoint-load-metrics-bin' => [Array],
      'grpc-server-stats-bin' => [Array],
      'google.rpc.errorinfo-bin' => [Array],
      'grpc-status-details-bin' => [Array]
    },
    options: {}
  },
  statusDetails: [
    ErrorInfo {
      metadata: [Object],
      reason: 'RESOURCE_PROJECT_INVALID',
      domain: 'googleapis.com'
    }
  ],
  reason: 'RESOURCE_PROJECT_INVALID',
  domain: 'googleapis.com',
  errorInfoMetadata: {
    method: 'google.longrunning.Operations.GetOperation',
    service: 'cloudfunctions.googleapis.com'
  }
}
mohanagy commented 10 months ago

I'm facing the same issue , and it happens when you call longRunningOperation.promise() I'm still trying to find the reason

skymakerolof commented 10 months ago

Found a workaround by using the https://www.npmjs.com/package/googleapis package instead. Something like this should work:

const googleAuth = new google.auth.GoogleAuth({
  keyFile: 'path/to/keyFile',
  scopes: ['https://www.googleapis.com/auth/cloud-platform'],
})

const cloudfunctions = google.cloudfunctions({
  version: 'v1',
  auth: googleAuth,
})

const functions = cloudfunctions.projects.locations.functions
const operations = cloudfunctions.operations

const functionOperationResponse = functions.create({ location, requestBody })

let operationResponse
for (let i = 0; i <= 60; i++) {
  operationResponse = await operations.get({
    name: functionOperationResponse.data.name,
  })

  if (operationResponse.data.done) break

  await new Promise((r) => setTimeout(r, 3000))
}