feat: integrate observability
This commit is contained in:
14
packages/observability/src/analytics/noop.test.ts
Normal file
14
packages/observability/src/analytics/noop.test.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { NoopAnalyticsService } from "./noop";
|
||||
|
||||
describe("NoopAnalyticsService", () => {
|
||||
it("should not throw on track", () => {
|
||||
const service = new NoopAnalyticsService();
|
||||
expect(() => service.track("test")).not.toThrow();
|
||||
});
|
||||
|
||||
it("should not throw on trackPageview", () => {
|
||||
const service = new NoopAnalyticsService();
|
||||
expect(() => service.trackPageview()).not.toThrow();
|
||||
});
|
||||
});
|
||||
15
packages/observability/src/analytics/noop.ts
Normal file
15
packages/observability/src/analytics/noop.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import type { AnalyticsService, AnalyticsEventProperties } from "./service";
|
||||
|
||||
/**
|
||||
* No-operation analytics service.
|
||||
* Used when analytics are disabled or for local development.
|
||||
*/
|
||||
export class NoopAnalyticsService implements AnalyticsService {
|
||||
track(eventName: string, props?: AnalyticsEventProperties): void {
|
||||
// Do nothing
|
||||
}
|
||||
|
||||
trackPageview(url?: string): void {
|
||||
// Do nothing
|
||||
}
|
||||
}
|
||||
31
packages/observability/src/analytics/service.ts
Normal file
31
packages/observability/src/analytics/service.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* Type definition for analytics event properties.
|
||||
*/
|
||||
export type AnalyticsEventProperties = Record<
|
||||
string,
|
||||
string | number | boolean | null | undefined
|
||||
>;
|
||||
|
||||
/**
|
||||
* Interface for analytics service implementations.
|
||||
*
|
||||
* This interface defines the contract for all analytics services,
|
||||
* allowing for different implementations (Umami, Google Analytics, etc.)
|
||||
* while maintaining a consistent API.
|
||||
*/
|
||||
export interface AnalyticsService {
|
||||
/**
|
||||
* Track a custom event with optional properties.
|
||||
*
|
||||
* @param eventName - The name of the event to track
|
||||
* @param props - Optional event properties (metadata)
|
||||
*/
|
||||
track(eventName: string, props?: AnalyticsEventProperties): void;
|
||||
|
||||
/**
|
||||
* Track a pageview.
|
||||
*
|
||||
* @param url - The URL to track (defaults to current location)
|
||||
*/
|
||||
trackPageview(url?: string): void;
|
||||
}
|
||||
74
packages/observability/src/analytics/umami.test.ts
Normal file
74
packages/observability/src/analytics/umami.test.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { UmamiAnalyticsService } from "./umami";
|
||||
|
||||
describe("UmamiAnalyticsService", () => {
|
||||
const mockConfig = {
|
||||
websiteId: "test-website-id",
|
||||
apiEndpoint: "https://analytics.test",
|
||||
enabled: true,
|
||||
};
|
||||
|
||||
const mockLogger = {
|
||||
debug: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
trace: vi.fn(),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
global.fetch = vi.fn();
|
||||
});
|
||||
|
||||
it("should not send payload if disabled", async () => {
|
||||
const service = new UmamiAnalyticsService({
|
||||
...mockConfig,
|
||||
enabled: false,
|
||||
});
|
||||
service.track("test-event");
|
||||
expect(global.fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should send payload with correct data for track", async () => {
|
||||
const service = new UmamiAnalyticsService(mockConfig, mockLogger);
|
||||
|
||||
(global.fetch as any).mockResolvedValue({ ok: true });
|
||||
|
||||
service.track("test-event", { foo: "bar" });
|
||||
|
||||
// Wait for async sendPayload
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
expect(global.fetch).toHaveBeenCalledWith(
|
||||
"https://analytics.test/api/send",
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
body: expect.stringContaining('"type":"event"'),
|
||||
}),
|
||||
);
|
||||
|
||||
const callBody = JSON.parse((global.fetch as any).mock.calls[0][1].body);
|
||||
expect(callBody.payload.name).toBe("test-event");
|
||||
expect(callBody.payload.data.foo).toBe("bar");
|
||||
expect(callBody.payload.website).toBe("test-website-id");
|
||||
});
|
||||
|
||||
it("should log warning if send fails", async () => {
|
||||
const service = new UmamiAnalyticsService(mockConfig, mockLogger);
|
||||
|
||||
(global.fetch as any).mockResolvedValue({
|
||||
ok: false,
|
||||
status: 500,
|
||||
text: () => Promise.resolve("Internal error"),
|
||||
});
|
||||
|
||||
service.track("test-event");
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
|
||||
expect(mockLogger.warn).toHaveBeenCalledWith(
|
||||
"Umami API responded with error",
|
||||
expect.objectContaining({ status: 500 }),
|
||||
);
|
||||
});
|
||||
});
|
||||
115
packages/observability/src/analytics/umami.ts
Normal file
115
packages/observability/src/analytics/umami.ts
Normal file
@@ -0,0 +1,115 @@
|
||||
import type { AnalyticsService, AnalyticsEventProperties } from "./service";
|
||||
|
||||
export interface UmamiConfig {
|
||||
websiteId?: string;
|
||||
apiEndpoint: string; // The endpoint to send to (proxied or direct)
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
export interface Logger {
|
||||
debug(msg: string, data?: any): void;
|
||||
warn(msg: string, data?: any): void;
|
||||
error(msg: string, data?: any): void;
|
||||
trace(msg: string, data?: any): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Umami Analytics Service Implementation (Script-less/Proxy edition).
|
||||
*/
|
||||
export class UmamiAnalyticsService implements AnalyticsService {
|
||||
private logger?: Logger;
|
||||
|
||||
constructor(
|
||||
private config: UmamiConfig,
|
||||
logger?: Logger,
|
||||
) {
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
private async sendPayload(type: "event", data: Record<string, any>) {
|
||||
if (!this.config.enabled) return;
|
||||
|
||||
const isClient = typeof window !== "undefined";
|
||||
const websiteId = this.config.websiteId;
|
||||
|
||||
if (!isClient && !websiteId) {
|
||||
this.logger?.warn(
|
||||
"Umami tracking called on server but no Website ID configured",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const payload = {
|
||||
website: websiteId,
|
||||
hostname: isClient ? window.location.hostname : "server",
|
||||
screen: isClient
|
||||
? `${window.screen.width}x${window.screen.height}`
|
||||
: undefined,
|
||||
language: isClient ? navigator.language : undefined,
|
||||
referrer: isClient ? document.referrer : undefined,
|
||||
...data,
|
||||
};
|
||||
|
||||
this.logger?.trace("Sending analytics payload", { type, url: data.url });
|
||||
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), 10000);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.config.apiEndpoint}/api/send`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"User-Agent": isClient ? navigator.userAgent : "Mintel-Server",
|
||||
},
|
||||
body: JSON.stringify({ type, payload }),
|
||||
keepalive: true,
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
clearTimeout(timeoutId);
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
this.logger?.warn("Umami API responded with error", {
|
||||
status: response.status,
|
||||
error: errorText.slice(0, 100),
|
||||
});
|
||||
}
|
||||
} catch (fetchError) {
|
||||
clearTimeout(timeoutId);
|
||||
if ((fetchError as Error).name === "AbortError") {
|
||||
this.logger?.error("Umami request timed out");
|
||||
} else {
|
||||
throw fetchError;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger?.error("Failed to send analytics", {
|
||||
error: (error as Error).message,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
track(eventName: string, props?: AnalyticsEventProperties) {
|
||||
this.sendPayload("event", {
|
||||
name: eventName,
|
||||
data: props,
|
||||
url:
|
||||
typeof window !== "undefined"
|
||||
? window.location.pathname + window.location.search
|
||||
: undefined,
|
||||
});
|
||||
}
|
||||
|
||||
trackPageview(url?: string) {
|
||||
this.sendPayload("event", {
|
||||
url:
|
||||
url ||
|
||||
(typeof window !== "undefined"
|
||||
? window.location.pathname + window.location.search
|
||||
: undefined),
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user