firebase cloud function with N-API deployment failed

88 Views Asked by At

Trying to find out if it's possible to run firebase cloud functions with native code (using N-API). I have a simple "hello world" example which works fine under emulator, however when I try to deploy it I get INVALID_ARGUMENT error:

  status: {
   code:  3     
   message:  "INVALID_ARGUMENT"     
  }

That's is not very informative... Just wondering if someone could shed some light on the situation. Thanks!

here is the function:

'use strict';

const functions = require('firebase-functions');

exports.helloWorld = functions.https.onRequest(async(request, response) => {

console.time('Program runtime');

const testAddon = require('bindings')('testaddon.node')
const {promisify} = require('util');

module.exports = testAddon;
const asyncCommand = testAddon.hello();

try {
  const result = await asyncCommand;
  console.log('CONTENT:', result);
  response.send(result);
}
catch (err) {
    console.log('ERROR:', err);
    response.send('ERROR:', err);
}

console.timeEnd('Program runtime');
});

and corresponding C++ source:

#include <napi.h>
namespace functionexample {
  std::string hello();
  Napi::String HelloWrapped(const Napi::CallbackInfo& info);
  Napi::Object Init(Napi::Env env, Napi::Object exports);
}
#include "functionexample.h"
std::string functionexample::hello(){
  return "Hello World";
}
Napi::String functionexample::HelloWrapped(const Napi::CallbackInfo& info)
{
  Napi::Env env = info.Env();
  Napi::String returnValue = Napi::String::New(env, functionexample::hello());

  return returnValue;
}
Napi::Object functionexample::Init(Napi::Env env, Napi::Object exports)
{
  exports.Set(
"hello", Napi::Function::New(env, functionexample::HelloWrapped)
  );

  return exports;
}
3

There are 3 best solutions below

0
On BEST ANSWER

It seems that the problem was with a version of the node engine. I've switched to node10 instead of node8 and my test function deploys properly and works as expected.

1
On

i'd guess the problem is that testaddon.hello() doesn't return a promise so awaiting on it is a problem. if addon.hello() was an async javascript function then javascript would assure that it returned a promise, but it's a C++ function.

i haven't used promises from an addon before but this might help:

https://github.com/nodejs/node-addon-api/blob/master/doc/promises.md

0
On

N-API has been marked like stable API starting from Node.js v8.6.0 so if you use an early version of the Node.js runtime you could meet problems like reported here. This is the reason because switching to Node.js version 10 all works well.