适用于 Firebase 的云函数:在不触及最大超时的情况下完成长时间的流程



当视频上传到Firebase存储时,我必须将视频从webm转码为mp4。我这里有一个可以工作的代码演示,但如果上传的视频太大,Firebase 函数将在转换完成之前超时。我知道可以增加函数的超时限制,但这似乎很混乱,因为我无法确认该过程花费的时间会少于超时限制。

有没有办法在不增加最大超时限制的情况下阻止 Firebase 超时?

如果没有,有没有办法完成耗时的过程(如视频转换),同时仍然让每个过程开始使用 firebase 函数触发器?

如果即使使用Firebase函数完成耗时的过程也不是真正存在的东西,那么有没有办法在不影响质量的情况下加快流畅ffmpeg的转换?(我意识到这部分有很多问题要问。如果绝对必要,我计划降低质量,因为 webms 转换为 mp4 的原因是用于 IOS 设备)

作为参考,这是我提到的演示的主要部分。正如我之前所说,完整的代码可以在这里看到,但是复制的这部分代码是创建确保转码完成的 Promise 的部分。完整的代码只有 70 行,所以如果需要,应该相对容易通过。

const functions = require('firebase-functions');
const mkdirp = require('mkdirp-promise');
const gcs = require('@google-cloud/storage')();
const Promise = require('bluebird');
const ffmpeg = require('fluent-ffmpeg');
const ffmpeg_static = require('ffmpeg-static');

(这里有一堆文本解析代码,然后是onChange事件中的下一个代码块)

function promisifyCommand (command) {
return new Promise( (cb) => {
command
.on( 'end',   ()      => { cb(null)  } )
.on( 'error', (error) => { cb(error) } )
.run();
})
}
return mkdirp(tempLocalDir).then(() => {
console.log('Directory Created')
//Download item from bucket
const bucket = gcs.bucket(object.bucket);
return bucket.file(filePath).download({destination: tempLocalFile}).then(() => {
console.log('file downloaded to convert. Location:', tempLocalFile)
cmd = ffmpeg({source:tempLocalFile})
.setFfmpegPath(ffmpeg_static.path)
.inputFormat(fileExtension)
.output(tempLocalMP4File)
cmd = promisifyCommand(cmd)
return cmd.then(() => {
//Getting here takes forever, because video transcoding takes forever!
console.log('mp4 created at ', tempLocalMP4File)
return bucket.upload(tempLocalMP4File, {
destination: MP4FilePath
}).then(() => {
console.log('mp4 uploaded at', filePath);
});
})
});
});

Cloud Functions for Firebase 不太适合(也不支持)可能超过最大超时时间的长时间运行的任务。使用云函数执行非常繁重的计算操作的唯一真正机会是找到一种方法将工作拆分为多个函数调用,然后将所有工作的结果合并到最终产品中。 对于像视频转码这样的事情,这听起来是一项非常艰巨的任务。

相反,请考虑使用函数在 App Engine 或 Compute Engine 中触发长时间运行的任务。

作为试图弄清楚如何通过视频转码或其他一些长过程的随机匿名者的跟进,这是我给出的相同代码示例的一个版本,它向 google 应用引擎进程发送 http 请求,该进程对文件进行转码。目前还没有这方面的文档,但查看Firebase/functions/index.js代码和app.js代码可能会帮助您解决问题。

https://github.com/Scew5145/GCSConvertDemo

祝你好运。

最新更新