Skip to content

Technical Patterns Reference

This document provides central reference for technical patterns used across Teams features. Feature documentation should link here instead of repeating these patterns.

Real-time Collaboration (Yjs/CRDT)

Teams uses Yjs (CRDT library) for conflict-free real-time collaboration.

Key Characteristics:

  • Collaborative editing without conflicts
  • Offline-capable with automatic sync
  • State persisted to PostgreSQL + IndexedDB
  • Custom WebSocket provider (ADR-0008)

Integration Pattern:

// Feature components use Yjs for shared state
import { useYjs } from '@/composables/useYjs'

const { doc, provider, awareness } = useYjs(threadId)

See: ADR-0007, ADR-0008

Thread Events (NOTIFY to SSE)

Changes to threads are propagated server-side (ADR-0023). Nothing is published from the browser.

Backend Pattern: publish inside the write transaction, so the event is bound to the commit.

import { publishThreadEvent } from '../../../events/publish.ts'
import { actorOf } from '../../../events/types.ts'

await db.transaction(async (tx) => {
  await tx.update(threads).set({ status }).where(...)
  await tx.insert(actions).values({ type: 'status', ... })
  await publishThreadEvent(tx, { type: 'thread.changed', inboxId, threadId, actor: actorOf(req.user) })
})

Events carry identifiers only (thread.changed, thread.created, inbox.synced, thread.mention, thread.assigned); clients re-fetch through the REST API. Emit one inbox.synced per mail import, never one event per imported thread.

Delivery: one LISTEN connection per replica (src/events/pg-listener.ts, owned by src/plugins/thread-events.ts) receives every NOTIFY and fans it out to the user's open Server-Sent Events connections (GET /api/events, src/routes/api/events/events.ts). Targeted events (mention, assigned) go to the target user only; inbox events go to inbox members.

Frontend Pattern: the store reacts to events by re-fetching, and re-fetches the visible state on every reconnect and when the tab becomes visible, so correctness never depends on push.

teamsEvents.on((event) => threadsStore.handleThreadEvent(event))
teamsEvents.onResync(() => refreshCurrentView())

API Endpoint Conventions

Filtering:

  • Query param format: ?filter=key:value,key2:value2
  • Common filters: status:active, status:done, tag:urgent
  • Server-side filtering required (never client-side for large datasets)

Response Format:

{
  "success": true,
  "data": [...],
  "meta": {
    "total": 100,
    "page": 1
  }
}

Error Format:

{
  "success": false,
  "error": {
    "code": "ERROR_CODE",
    "message": "Human-readable message"
  }
}

State Management (Pinia)

Store Pattern:

// stores/feature.js
import { defineStore } from 'pinia'

export const useFeatureStore = defineStore('feature', () => {
  // State
  const items = ref([])

  // Actions
  async function fetchItems() {
    const response = await api.get('/items')
    items.value = response.data
  }

  return { items, fetchItems }
})

Optimistic Updates:

async function updateItem(id, data) {
  // Update locally first
  const index = items.value.findIndex(i => i.id === id)
  const original = items.value[index]
  items.value[index] = { ...original, ...data }

  try {
    await api.put(`/items/${id}`, data)
  } catch (error) {
    // Rollback on failure
    items.value[index] = original
    throw error
  }
}

Database Transactions

Transaction Pattern:

// Use database transactions for related updates
await fastify.db.transaction(async (tx) => {
  await tx.update(threads).set({ status: 'done' })
  await tx.insert(actions).values({ type: 'status', ... })
  // Publish the thread event inside the transaction (delivered on commit)
  await publishThreadEvent(tx, { type: 'thread.changed', inboxId, threadId })
})

Foreign Key Cascades:

  • Use ON DELETE CASCADE for automatic cleanup
  • Example: thread_id REFERENCES threads(id) ON DELETE CASCADE

Authentication & Authorization

Permission Check Pattern:

// Check user has access to thread's inbox
const hasAccess = await fastify.db.query.accounts.findFirst({
  where: and(
    eq(accounts.userId, userId),
    eq(accounts.inboxId, thread.inboxId)
  )
})

if (!hasAccess) {
  throw fastify.httpErrors.forbidden()
}

See: ADR-0011

Testing Patterns

See: docs/development/testing.md, docs/development/e2e-testing.md