I am working on a Node Azure Function (on Linux) to create a GIF image on the fly. It all works wonderfully on my local MacBook, but fails when I deploy to Azure.
When peaking into the Logs, I just see it throws a Microsoft.Azure.WebJobs.Script.Workers.Rpc.RpcException
in logs when deployed to Azure.
Below is my in-progress code. I have included the full function code as there is no obvious (to me) indication of the error source. Does anyone have any ideas what may be causing this issue?
import { AzureFunction, Context, HttpRequest } from "@azure/functions"
import { DateTime, Duration } from "luxon";
import { Canvas } from "canvas";
import * as fs from 'fs';
const os = require('os');
const { GifEncoder } = require("@skyra/gifenc")
const { buffer } = require('node:stream/consumers');
const httpTrigger: AzureFunction = async function (context: Context, req: HttpRequest): Promise<void> {
try {
let countdownTo: string = req.query.countdownTo || DateTime.now().plus({days: 7}).toFormat("yyyy-LL-dd'T'T");
let width: number = parseInt(req.query.width) || 300;
let height: number = parseInt(req.query.height);
let frames: number = parseInt(req.query.frames) || 180;
let background: string = '#' (req.query.background || '000e4e');
let foreground: string = '#' (req.query.foreground || '00b7f1');
// Set height to 1/3 width if not specified
if (!height) {
height = width/3;
}
// ========================================================================
// Set upper and lower limits
width = Math.max(width, Math.min(120, 640));
height = Math.max(height, Math.min(120, 640));
frames = Math.max(frames, Math.min(1, 600));
// Time calculations
const nowDate: DateTime = DateTime.now()
const targetDate: DateTime = DateTime.fromISO(countdownTo); // "2022-11-01T12:00"
let timeDifference: Duration = targetDate.diff(nowDate);
// ========================================================================
const encoder: any = new GifEncoder(width, height);
const canvas: Canvas = new Canvas(width, height);
const ctx: any = canvas.getContext('2d');
let fileName = targetDate.toFormat('yyyyLLddHHmmss') '-' nowDate.toFormat('yyyyLLddHHmmss') '.gif';
// Specify temporary directory and create if it doesn't exist
const temporaryFileDirectory: string = os.tmpdir() '/tmp/';
if (!fs.existsSync(temporaryFileDirectory)) {
fs.mkdirSync(temporaryFileDirectory);
}
// Stream the GIF data into a file
let filePath: string = temporaryFileDirectory fileName '.gif';
const readStream = encoder.createReadStream()
readStream.pipe(fs.createWriteStream(filePath));
// Set the font size, style, and alignment
let fontSize: string = Math.floor(width/12) 'px';
let fontFamily: string = 'Arial';
ctx.font = [fontSize, fontFamily].join(' ');
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
// Start Encoding GIF
encoder.setRepeat(0).setDelay(1000).setQuality(10).start();
if (timeDifference.milliseconds <= 0) { // Date has passed
context.log('EXPIRED Date:', countdownTo);
// Set Canvas background color
ctx.fillStyle = background;
ctx.fillRect(0, 0, width, height);
// Print Text
ctx.fillStyle = foreground;
ctx.fillText('Date has passed!', (width/2), (height/2));
// Add frame to the GIF
encoder.addFrame(ctx);
}
else { // Date is in the future
timeDifference = targetDate.diff(DateTime.now(), ['days', 'hours', 'minutes', 'seconds']);
context.log('Date:', countdownTo);
for (let i: number = 0; i < frames; i ) {
// Extract the duration from the days
let days: number = Math.floor(timeDifference.days);
let hours: number = Math.floor(timeDifference.hours);
let minutes: number = Math.floor(timeDifference.minutes);
let seconds: number = Math.floor(timeDifference.seconds);
let daysDisplay: any = (days.toString().length == 1) ? '0' days : days;
let hoursDisplay: any = (hours.toString().length == 1) ? '0' hours : hours;
let minutesDisplay: any = (minutes.toString().length == 1) ? '0' minutes : minutes;
let secondsDisplay: any = (seconds.toString().length == 1) ? '0' seconds : seconds;
// Create the text to be displayed
let displayText: string = [daysDisplay, 'd ', hoursDisplay, 'h ', minutesDisplay, 'm ', secondsDisplay, 's'].join('');
//context.log(displayText);
// Set Canvas background color
ctx.fillStyle = background;
ctx.fillRect(0, 0, width, height);
// Print Text
ctx.fillStyle = foreground;
ctx.fillText(displayText, (width/2), (height/2));
// Add frame to the GIF
encoder.addFrame(ctx);
// Remove a second in preparation for the next frame
if (seconds < 1) {
if (minutes < 1) {
if (hours < 1) {
timeDifference = timeDifference.minus({days: 1});
}
timeDifference = timeDifference.minus({hours: 1});
}
timeDifference = timeDifference.minus({minutes: 1});
timeDifference = timeDifference.plus({seconds: 59});
}
else {
timeDifference = timeDifference.minus({seconds: 1});
}
}
}
// Encoding complete...
encoder.finish();
const fileData = await buffer(readStream);
//context.log(fileData);
context.res = {
headers: {
"Content-Type": "image/gif"
},
isRaw: true,
status: 200,
body: new Uint8Array(fileData)
};
fs.unlinkSync(filePath)
}
catch(ex: any) {
context.res = {
status: 200,
body: ex.message
};
}
};
export default httpTrigger;
CodePudding user response:
I discovered that this issue was related to an issue with Azure DevOps pipeline. The pipeline indicated that it had ran successfully, but it never installed any node_modules.
The node_modules folder on the Function App was empty after deployment, causing references to things like Luxon to fail completely.
I switched to Github Actions and it worked fine, so apparently some step was incorrect in the pipeline.
If you run into an issue with a particular function working perfectly locally, but not in production -- double check to ensure that your CI/CD pipelines are working successfully.