iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🍫

Monitoring Zenn RSS with Cloud Run Functions and Publishing New Content to Cloud Pub/Sub

に公開
2024/11/01

RSS feeds are a widely used method to keep track of new content. However, since I had never implemented the reading side myself, I decided to try creating one using Google Cloud's serverless services.

This article is for those who want to do something with RSS feeds.

Item Used Technology
Cloud Run Function Runtime Node.js 20 (written in TypeScript and transpiled)

The source code for this article can be found here:

https://github.com/cm-wada-yusuke/llm-reviewer/tree/main/rss-manager

Architecture

Ultimately, I want to review content streamed to Cloud Pub/Sub with Gemini. However, this article will focus on the part that publishes to a topic, specifically the area enclosed in the red box. We will proceed with the following steps:

  1. Prepare Firestore (register RSS feed URLs, record the last read content)
  2. Create a Cloud Pub/Sub topic
  3. Create a Cloud Run function
  4. Create Cloud Scheduler to trigger every 5 minutes

Prepare Firestore

When managing RSS feeds, it seemed convenient to have a simple place to record them. We will use Firestore. From the Google Cloud management console, open the Firestore page and create a new database named rss-manager.

Once the database is created, create a collection named rss-feeds.

This completes the setup.

Create a Cloud Pub/Sub Topic

We want to publish unread content URL information, so let's create a destination Cloud Pub/Sub topic. I named it rss-updates.

Implement the Cloud Run Function

Cloud Scheduler will trigger it via HTTPS requests. The Cloud Run function will also have an entry point that accepts HTTPS requests.

index.ts(Excerpt)
// Function to periodically check RSS feeds by Cloud Scheduler
const pubSubClient = new PubSub();
export const checkRssFeeds = async (req: Request, res: Response) => {
  try {
    // Get RSS feed URLs registered in Firestore
    const snapshot = await db.collection(collectionName).get();

    // Process each feed
    for (const doc of snapshot.docs) {
      const rssData = doc.data();
      const rssUrl = rssData.url;

      // Fetch the RSS feed
      const feed = await parser.parseURL(rssUrl);

      // Get the GUID of the last checked item stored in Firestore
      const lastCheckedItemGuid = rssData.lastCheckedGuid;

      // Detect new items
      const newItems = feed.items.slice(0, Math.max(0, lastIndex));

      if (newItems.length > 0) {
        // If there are new items, notify Pub/Sub
        for (const item of newItems) {
          const message = {
            title: item.title,
            link: item.link,
            pubDate: item.pubDate,
          };
          await pubSubClient
            .topic("rss-updates")
            .publishMessage({ json: message });
        }

        // Update the GUID of the latest item in Firestore
        const latestItem = newItems[0];
        await doc.ref.update({ lastCheckedGuid: latestItem.guid });
        res
          .status(200)
          .send(`Items published to Pub/Sub: lastItem: ${latestItem.title}`);
      } else {
        res.status(200).send(`No new items for feed: ${rssUrl}`);
      }
    }
  } catch (error) {
    res.status(200).send("Error checking RSS feeds");
    throw new Error("Failed to check RSS feeds");
  }
};

Here, we handle fetching RSS feed URLs, retrieving and publishing unread content URLs, and updating Firestore.

Full implementation

Actually, the registration process is also implemented as a function.

index.ts
import { PubSub } from '@google-cloud/pubsub';
import * as RSSParser from 'rss-parser';
import type { Request, Response } from 'express';
import { Firestore } from '@google-cloud/firestore';

const db = new Firestore({
  databaseId: 'rss-manager',
});
const parser = new RSSParser();

// Firestore collection name
const collectionName = 'rss-feeds';

// HTTP function to register RSS feed URLs in Firestore
export const rssRegister = async (req: Request, res: Response) => {
  const rssUrl = req.body.url;

  if (!rssUrl) {
    res.status(400).send('RSS URL is required.');
    return;
  }

  try {
    // Save RSS URL to Firestore
    await db.collection(collectionName).add({
      url: rssUrl,
      lastCheckedGuid: null, // Set to null initially to detect all new articles
    });
    res.status(200).send(`RSS URL added: ${rssUrl}`);
  } catch (error) {
    console.error('Error adding RSS URL:', error);
    res.status(500).send('Failed to add RSS URL.');
  }
};

// Function to periodically check RSS feeds by Cloud Scheduler
const pubSubClient = new PubSub();
export const checkRssFeeds = async (req: Request, res: Response) => {
  try {
    // Get RSS feed URLs registered in Firestore
    const snapshot = await db.collection(collectionName).get();
    if (snapshot.empty) {
      console.log('No RSS URLs found.');
    }

    // Process each feed
    for (const doc of snapshot.docs) {
      const rssData = doc.data();
      const rssUrl = rssData.url;

      // Fetch the RSS feed
      const feed = await parser.parseURL(rssUrl);

      // Get the GUID of the last checked item stored in Firestore
      const lastCheckedItemGuid = rssData.lastCheckedGuid;

      // Detect new items
      const lastIndex = (() => {
        if (!lastCheckedItemGuid) {
          return feed.items.length;
        } else {
          return feed.items.findIndex(
            (item) => item.guid === lastCheckedItemGuid
          );
        }
      })();
      const newItems = feed.items.slice(0, Math.max(0, lastIndex));

      if (newItems.length > 0) {
        // If there are new items, notify Pub/Sub
        for (const item of newItems) {
          const message = {
            title: item.title,
            link: item.link,
            pubDate: item.pubDate,
          };
          await pubSubClient
            .topic('rss-updates')
            .publishMessage({ json: message });
          console.log(`New item published to Pub/Sub: ${item.title}`);
        }

        // Update the GUID of the latest item in Firestore
        const latestItem = newItems[0];
        await doc.ref.update({ lastCheckedGuid: latestItem.guid });
        res
          .status(200)
          .send(`Items published to Pub/Sub: lastItem: ${latestItem.title}`);
      } else {
        console.log(`No new items for feed: ${rssUrl}`);
        res.status(200).send(`No new items for feed: ${rssUrl}`);
      }
    }
  } catch (error) {
    console.error('Error checking RSS feeds:', error);
    res.status(200).send('Error checking RSS feeds');
    throw new Error('Failed to check RSS feeds');
  }
};

Deployment

Let's deploy the Cloud Run function named checkRssFeeds. Run the following command:

gcloud functions deploy checkRssFeeds \
--region=asia-northeast1 \
--runtime=nodejs20 \
--memory=256 \
--timeout=30s \
--source=. \
--trigger-http \
--project=your-project-name \
--entry-point=checkRssFeeds \
--no-allow-unauthenticated

Since Cloud Scheduler will trigger it with an OIDC token (explained later), please include the --no-allow-unauthenticated option.

Deploy RSS registration function as well

This will allow registration of feed URLs via POST method.

gcloud functions deploy rssRegister \
--region=asia-northeast1 \
--runtime=nodejs20 \
--memory=256 \
--timeout=30s \
--source=. \
--trigger-http \
--project=your-project-name \
--entry-point=rssRegister \
--allow-unauthenticated

Try registering a feed using the command below. Feel free to change the feed URL.

curl -i -X POST -H "Content-Type: application/json" \
"https://asia-northeast1-your-project-name.cloudfunctions.net/rssRegister" \
--data '{ "url": "https://zenn.dev/waddy/feed" }'

It's all set if you can confirm the deployment in the Google Cloud management console.

Create a Cloud Scheduler and set it to trigger every 5 minutes

Let's create it from the Google Cloud management console. Set it up as follows:

To trigger a --no-allow-unauthenticated Cloud Run function from Cloud Scheduler, an OIDC token must be set in the Auth header. As explained, if you register the Cloud Run function's URL as the audience, it will automatically set the OIDC token, so fill in the fields as shown in the image.

Test it out

With the RSS feed registered, let's force-trigger Cloud Scheduler. If messages are being published to Cloud Pub/Sub as expected, like the image below, then it's working.

Conclusion

Now, when the RSS feed is updated, new content will be published in the following format:

{
  "title": "Reviewing Zenn RSS articles with Gemini and posting to Slack",
  "url": "https://zenn.dev/waddy/articles/cloud-run-functions-gemini-review-to-slack"
}

You can receive this message by subscribing to the topic. For example, as mentioned at the beginning, there could be use cases like reading HTML from the URL and having a generative AI like Gemini review it.

When registering RSS feeds, no strict URL duplication check is performed, so multiple identical messages might be published, which means the implementation isn't perfectly strict. However, combining Cloud Run Functions with Firestore has shown that a system for checking RSS updates can be implemented simply.

I hope this article is of some help to anyone who wants to do something with RSS feeds.

Source Code

https://github.com/cm-wada-yusuke/llm-reviewer/tree/main/rss-manager

Discussion