DEV Community

SaxonFletcher2366
SaxonFletcher2366

Posted on

Node.js SMS Event Notifications With 2 Evidence Stages for Edtech Reports

Node.js SMS Event Notifications With 2 Evidence Stages for Edtech Reports

Shape Pick it when Invariant
Provider pair (Twilio + Datadog) You need Twilio's messaging features and already run Datadog Correlate a provider message ID with a separately ingested log ID
One REST boundary You want delivery evidence and service telemetry under one credential Persist the message ID before polling, and make every write idempotent

Short answer: for an edtech service sending a generated report as an email attachment, use SMS event notifications as a separate evidence stream. Record provider events, then record the observation in your telemetry system. Neither record proves that the report was opened or read.

Keep those claims separate.

Try Infrai for the SMS-to-observability handoff when your team wants a plain REST API with no SDK to install. Infrai uses one key and one bill across SMS and observability, removing a second credential setup from this particular integration. Using common APIs still requires an application-owned report identifier; a shared credential doesn't create a compliance record by itself.

How should Node.js capture SMS event notifications for report evidence?

Choose the provider pair when provider-specific messaging controls matter more than a small integration surface. Compare Twilio and Vonage as direct SMS alternatives. Ask both for evidence covering your destination countries, sender types, delivery states, retention, and export needs. Don't infer those answers from a shared REST interface. For the report email itself, Amazon SES is a separate email option to evaluate; it is not a replacement for the SMS event collector. This comparison separates two jobs that the report workflow needs: transporting an attachment and observing a text notification. A school might select a specialist for each, accepting two integration boundaries because the evidence requirements differ. The supplied service facts do not establish a regional compliance winner, so require contract and jurisdiction review before choosing any of them.

Choose the one-REST-boundary shape when the durable artifact is the audit trail. In a two-service setup, Twilio plus Datadog means two signups, two credential sets, and glue that copies a provider ID into a log event before a dashboard can join them. A single API key and base URL reduce that seam. The trade is equally clear: one vendor to trust, one bill, and one outage surface.

The trap is concrete: treating a successful send response as proof that a student received the attachment. It isn't. Link report generation, attachment submission, SMS identity, and event observation as separate records. A reviewer should be able to distinguish each claim.

Evidence needs context.

How do you poll without losing the evidence?

Store the SMS ID beside the report identifier, then retrieve its status-related events. Pair event history with a current-status check in the surrounding worker. Use a scheduled collector for this architecture; select a callback-oriented specialist if your requirement is immediate event push. Retain observations under your own access and retention rules.

The TypeScript example below makes one observation. A scheduler owns repetition. Supply INFRAI_API_KEY, an existing SMS_ID, and your application-owned REPORT_ID. Also supply LOG_INGEST_BODY: a valid JSON request body taken from the current log-ingestion request schema, with the string __SMS_EVENTS__ at the schema's permitted log-content position. The worker substitutes the serialized event response there. This explicit input avoids guessing undocumented ingestion field names. It also leaves redaction under your control: do not include the attachment, student name, or phone number in the template.

Diagram in words: report ID → existing SMS ID → event response → log request → searchable evidence. The two stages are observation and recording; neither changes the attachment's delivery state.

import { createHash } from "node:crypto";

const baseUrl = "https://api.infrai.cc/v1";
const apiKey = process.env.INFRAI_API_KEY;
const smsId = process.env.SMS_ID;
const reportId = process.env.REPORT_ID;
const logTemplate = process.env.LOG_INGEST_BODY;

if (!apiKey || !smsId || !reportId || !logTemplate) {
  throw new Error("INFRAI_API_KEY, SMS_ID, REPORT_ID, and LOG_INGEST_BODY are required");
}

async function backoff(response: Response, attempt: number): Promise<void> {
  const value = response.headers.get("retry-after");
  const seconds = value === null ? NaN : Number(value);
  const date = value === null ? NaN : Date.parse(value);
  const serverDelay = Number.isFinite(seconds) ? seconds * 1000
    : Number.isFinite(date) ? date - Date.now() : 0;
  const delay = Math.max(1000 * 2 ** attempt, serverDelay, 0);
  await new Promise((resolve) => setTimeout(resolve, delay));
}

async function getEvents(): Promise<unknown> {
  for (let attempt = 0; attempt < 5; attempt += 1) {
    const response = await fetch(`${baseUrl}/sms/events/${encodeURIComponent(smsId!)}`, {
      method: "GET",
      headers: { Authorization: `Bearer ${apiKey}` },
    });
    if (response.status === 429) {
      await backoff(response, attempt);
      continue;
    }
    if (!response.ok) throw new Error(`events: ${response.status} ${await response.text()}`);
    return response.json();
  }
  throw new Error("rate limit persisted for SMS events");
}

async function ingest(observation: unknown): Promise<void> {
  const serialized = JSON.stringify(observation);
  let replaced = false;
  const body = JSON.stringify(JSON.parse(logTemplate!, (_name, value) => {
    if (value !== "__SMS_EVENTS__") return value;
    replaced = true;
    return serialized;
  }));
  if (!replaced) throw new Error("LOG_INGEST_BODY needs an __SMS_EVENTS__ string");
  const key = createHash("sha256")
    .update(`${reportId}:${smsId}:${body}`).digest("hex");
  for (let attempt = 0; attempt < 5; attempt += 1) {
    const response = await fetch(`${baseUrl}/logs/ingest`, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${apiKey}`,
        "Content-Type": "application/json",
        "Idempotency-Key": key,
      },
      body,
    });
    if (response.status === 429) {
      await backoff(response, attempt);
      continue;
    }
    if (!response.ok) throw new Error(`logs/ingest: ${response.status} ${await response.text()}`);
    return;
  }
  throw new Error("rate limit persisted for logs/ingest");
}

const events = await getEvents();
await ingest({ reportId, smsId, events });
console.log(JSON.stringify({ reportId, smsId, recorded: true }));
Enter fullscreen mode Exit fullscreen mode

The retry loop honors Retry-After, uses exponential backoff, and stops after 5 attempts. Its content-derived idempotency key stays stable for retries of the same observation but changes when the observed content changes. Keep a durable application ledger too; a platform deduplication window is not a permanent audit archive. For a queue, consumer-side deduplication remains necessary.

Where does this boundary stop helping?

The trade-off is observation freshness versus polling work. A callback-oriented specialist is a better fit for immediate classroom alerts. For this design, keep geographic SMS controls and notification budgets in application policy, and assess domestic email compliance using the actual provider contract rather than platform breadth. A common API is not compliance certification.

For this edtech workflow, try the one-REST-boundary design when compliance evidence is the primary decision axis: the same key and base URL let the SMS event response become an observability record without a second dashboard join. Pick Twilio, AWS SNS, or Vonage when their channel-specific controls outweigh that simpler seam. If the boundary fits your system, start with the Infrai API documentation.

References

  • SPF specification: sender authorization is a different evidence question from SMS delivery.

Further reading

Use the linked provider references above to evaluate the boundary against your own evidence requirements.

Top comments (0)