PSA/shared/services/email/providers/base/BaseEmailAdapter.ts
Hermes 284313f908
Some checks are pending
Bidi Control Character Guard / bidi-control-guard (push) Waiting to run
Circular Dependency Check / Check for new circular dependencies (push) Waiting to run
Citus Migration Smoke / Combined migrations on single-node Citus (push) Waiting to run
E2E Fresh Install Tests / fresh-install-e2e (push) Waiting to run
ext-v2 guardrails / Run ext-v2 guard and ESLint (push) Waiting to run
Integration Tests / Check for relevant changes (push) Waiting to run
Integration Tests / ${{ (github.event_name == 'schedule' || github.event.inputs.suite == 'full') && 'Full integration suite' || 'Tier-1 integration subset' }} (push) Blocked by required conditions
Mobile checks / Mobile lint + typecheck (push) Waiting to run
Mobile checks / Mobile unit tests (push) Waiting to run
Mobile checks / Mobile dependency audit (report) (push) Waiting to run
Mobile checks / Mobile reproducibility checks (push) Waiting to run
Secrets guard (env backups) / Ensure no tracked env backup files (push) Waiting to run
Temporal Readiness / fast-readiness (push) Waiting to run
Temporal Readiness / docker-parity (push) Waiting to run
TypeScript Type Check / Nx affected typecheck (push) Waiting to run
Unit Tests / Skipped-test budget (push) Waiting to run
Unit Tests / Nx affected unit tests (push) Waiting to run
Unit Tests / Server unit coverage (informational) (push) Waiting to run
Validate Tenant Management Schema / Check for relevant changes (push) Waiting to run
Validate Tenant Management Schema / Validate Tenant Management Schema (push) Blocked by required conditions
EE Workflows Build Guard / ee-workflows-build-guard (push) Waiting to run
Initial import of AlgaPSA codebase from PSA server
Excluded: .git, node_modules, secrets/, compose.env, assemblyscript tgz

Source: /opt/alga-psa on psa.joliet.tech
2026-06-22 16:12:17 -05:00

115 lines
4.0 KiB
TypeScript

import { EmailProviderAdapter } from '../../../../interfaces/emailProvider.interface';
import { EmailProviderConfig, EmailMessageDetails } from '../../../../interfaces/inbound-email.interfaces';
/**
* Base abstract class for email provider adapters
* Provides common functionality and enforces interface implementation
*/
export abstract class BaseEmailAdapter implements EmailProviderAdapter {
protected config: EmailProviderConfig;
protected accessToken?: string;
protected refreshToken?: string;
protected tokenExpiresAt?: Date;
constructor(config: EmailProviderConfig) {
this.config = config;
}
/**
* Get the current configuration
*/
getConfig(): EmailProviderConfig {
return this.config;
}
/**
* Check if the access token is expired or will expire soon
* @param bufferMinutes - Minutes of buffer before expiry (default: 5)
*/
protected isTokenExpired(bufferMinutes: number = 5): boolean {
if (!this.tokenExpiresAt) return true;
const now = new Date();
const bufferTime = bufferMinutes * 60 * 1000; // Convert to milliseconds
return (this.tokenExpiresAt.getTime() - now.getTime()) <= bufferTime;
}
/**
* Load stored credentials from the configuration
* This should be implemented by each provider to load their specific credential format
*/
protected abstract loadCredentials(): Promise<void>;
/**
* Refresh the access token using the refresh token
* This should be implemented by each provider using their OAuth flow
*/
protected abstract refreshAccessToken(): Promise<void>;
/**
* Ensure we have a valid access token, refreshing if necessary
*/
protected async ensureValidToken(): Promise<void> {
if (!this.accessToken) {
await this.loadCredentials();
}
if (this.isTokenExpired()) {
await this.refreshAccessToken();
}
}
/**
* Log messages with provider context
*/
protected log(level: 'info' | 'warn' | 'error', message: string, data?: any): void {
const logMessage = `[${this.config.provider_type.toUpperCase()}] ${message}`;
if (data) {
console[level](logMessage, data);
} else {
console[level](logMessage);
}
}
/**
* Handle errors consistently across providers
*/
protected handleError(error: any, context: string): Error {
// Try to extract helpful details from Axios-style errors
let details = '';
const res = error?.response;
if (res) {
const err = res.data?.error || res.data;
const code = err?.code || res.status;
const message = err?.message || res.statusText;
const inner = err?.innerError || err?.innererror;
const reqId = res.headers?.['request-id'] || res.headers?.['client-request-id'];
details = ` (code: ${code}${reqId ? `, request-id: ${reqId}` : ''}${inner?.dateTime ? `, time: ${inner.dateTime}` : ''})`;
}
const errorMessage = `Error in ${context}: ${error.message || error}${details}`;
this.log('error', errorMessage, error);
const wrapped = new Error(errorMessage);
// Propagate metadata for outer catch blocks
try {
(wrapped as any).status = res?.status;
(wrapped as any).code = (res?.data?.error?.code || res?.status) ?? undefined;
(wrapped as any).requestId = res?.headers?.['request-id'] || res?.headers?.['client-request-id'];
(wrapped as any).responseBody = res?.data;
} catch { /* no-op */ }
return wrapped;
}
// Abstract methods that must be implemented by each provider
abstract connect(): Promise<void>;
abstract registerWebhookSubscription(): Promise<void>;
abstract renewWebhookSubscription(): Promise<void>;
abstract processWebhookNotification(payload: any): Promise<string[]>;
abstract markMessageProcessed(messageId: string): Promise<void>;
abstract getMessageDetails(messageId: string): Promise<EmailMessageDetails>;
abstract downloadMessageSource(messageId: string): Promise<Buffer>;
abstract testConnection(): Promise<{ success: boolean; error?: string; }>;
abstract disconnect(): Promise<void>;
}