Back

[Solved] Document creation event not firing reliably

  • 0
  • Databases
  • Functions
  • Web
  • Cloud
PoppingPopper
13 Nov, 2023, 16:16

Hi, I'm loving Appwrite and how easy it is to get started.

I'm using a function that I've added a document create event to listen for. The event string looks like this databases.slack-events.collections.events.documents.*.create. I am however not seeing any executions for the function.

Here is the function

TypeScript
import { StatusCodes, getReasonPhrase } from 'http-status-codes'
import { WebClient } from '@slack/web-api'
import { Client, Databases } from 'node-appwrite'

export default async ({ req, res, log, error }: any) => {
  log(req.bodyRaw) // Raw request body, contains request data
  log(JSON.stringify(req.body)) // Object from parsed JSON request body, otherwise string
  log(JSON.stringify(req.headers)) // String key-value pairs of all request headers, keys are lowercase
  log(req.scheme) // Value of the x-forwarded-proto header, usually http or https
  log(req.method) // Request method, such as GET, POST, PUT, DELETE, PATCH, etc.
  log(req.url) // Full URL, for example: http://awesome.appwrite.io:8000/v1/hooks?limit=12&offset=50
  log(req.host) // Hostname from the host header, such as awesome.appwrite.io
  log(req.port) // Port from the host header, for example 8000
  log(req.path) // Path part of URL, for example /v1/hooks
  log(req.queryString) // Raw query params string. For example "limit=12&offset=50"
  log(JSON.stringify(req.query)) // Parsed query params. For example, req.query.limit

  const document = req.body as SlackEventDocument

  let err = null as string | null
  switch (document.event_type) {
    case 'app_mention':
      err = await handleAppMention(document)
      break
    default:
      error('Unhandled event type: ' + document.event_type)
      return res.send(getReasonPhrase(StatusCodes.OK), StatusCodes.OK)
  }

  if (err !== null) {
    error('Failed to handle event')
    error(err)
    return res.send(
      getReasonPhrase(StatusCodes.INTERNAL_SERVER_ERROR),
      StatusCodes.INTERNAL_SERVER_ERROR
    )
  }

  log('Successfully handled event')

  return res.send(getReasonPhrase(StatusCodes.OK), StatusCodes.OK)
}

const slackClient = new WebClient(Bun.env['SLACK_OAUTH'])

const appwriteClient = new Client()
appwriteClient
  .setEndpoint(Bun.env['APPWRITE_ENDPOINT'])
  .setProject(Bun.env['APPWRITE_PROJECT'])
const db = new Databases(appwriteClient)

async function handleAppMention(
  document: SlackEventDocument
): Promise<string | null> {
  //! test response to slack
  try {
    await slackClient.chat.postMessage({
      channel: document.event_channel_id,
      text: 'Hi there! you said: \n> ' + document.event_text,
    })
  } catch (err) {
    return err
  }

  // Delete the processed document
  try {
    await db.deleteDocument('slack-events', 'events', document.$id)
  } catch (err) {
    return err
  }

  return null
}

Here is the appwrite.json for that function

TypeScript
{
  "$id": "654ee4144ec39d66688a",
  "name": "Process Slack Event",
  "runtime": "bun-1.0",
  "execute": ["any"],
  "events": [
    "databases.slack-events.collections.events.documents.*.create"
  ],
  "schedule": "",
  "timeout": 15,
  "enabled": true,
  "logging": true,
  "entrypoint": "src/process-slack-event.ts",
  "commands": "bun install",
  "ignore": ["node_modules", ".npm"],
  "path": "./"
}
TL;DR
I am experiencing an issue where the document creation event in my function is not firing reliably. I have added a document create event to listen for in my function, but I am not seeing any executions for it. I am using Appwrite for this. Solution: It seems that there may be a spin-up time and sleep delay for events. This can cause delays in the firing of events. This may not be a problem in production, but it is something to be aware of.
PoppingPopper
13 Nov, 2023, 16:28

[Solved-ish] Document creation event not firing reliably

PoppingPopper
13 Nov, 2023, 16:29

Solved-ish, the first event I tested fired several minutes late even later than a subsequent test that fired pretty much immediately. Looks like there's a spin up time and sleep. Hope that's not a problem in production.

Kenny
13 Nov, 2023, 16:35

Functions will go to sleep after not being used for a certain amount of time, you can get around this by setting up a timer to ping the function every x seconds to keep it awake.

Kenny
13 Nov, 2023, 16:35
Drake
13 Nov, 2023, 16:59

Is this on Cloud or self-hosted?

PoppingPopper
13 Nov, 2023, 16:59

Cloud

Drake
13 Nov, 2023, 17:03

Executions can be either synchronous or asynchronous.

Synchronous executions happen when you hit the function URL or you call create execution with async = false. Synchronous executions happen right away.

Asynchronous executions are all other executions (like executions via an event). These are queued and then execute based on order and server load.

We've scaled Appwrite so that these asyncrhonous executions happen fast and aren't really delayed so I'm a little surprised you experience a delay. Do you have other functions executing based on this event?

PoppingPopper
13 Nov, 2023, 17:05

Oh that sounds lovely! I may not have it configured correctly then? I don't have other functions executing based on this event. Also I'm just building a small slack app so I don't see any more than this 1 function.

PoppingPopper
13 Nov, 2023, 17:05

I used the cli to build the function so not much manual configuration.

Drake
13 Nov, 2023, 17:05

Are you self-hosting or on cloud?

PoppingPopper
13 Nov, 2023, 17:05

Cloud

Drake
13 Nov, 2023, 17:06

Could you let me know the next time this happens?

PoppingPopper
13 Nov, 2023, 17:06

Sure thing!

PoppingPopper
13 Nov, 2023, 17:07

[Solved] Document creation event not firing reliably

Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more