Skip to content

Commit

Permalink
Added logpush client and done some restructuring
Browse files Browse the repository at this point in the history
  • Loading branch information
maddsua committed Jan 5, 2024
1 parent a23cf70 commit c6fd6db
Show file tree
Hide file tree
Showing 8 changed files with 197 additions and 5 deletions.
24 changes: 24 additions & 0 deletions .github/workflows/analytics-client.publish.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
name: Publish Analytics/Client Package

on:
push:
branches: ['main']
paths: ['client/analytics/package.json']

jobs:
npm_publish_client:
runs-on: ubuntu-latest
defaults:
run:
working-directory: client/analytics
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: 18
registry-url: https://registry.npmjs.org/
- run: npm ci
- run: npm run build
- run: npm publish --access public
env:
NODE_AUTH_TOKEN: ${{secrets.NPM_PUBLISH}}
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
name: Publish Client Package
name: Publish Logpush/Client Package

on:
push:
branches: ['main']
paths: ['client/package.json']
paths: ['client/logpush/package.json']

jobs:
npm_publish_client:
runs-on: ubuntu-latest
defaults:
run:
working-directory: client
working-directory: client/logpush
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
Expand Down
File renamed without changes.
4 changes: 2 additions & 2 deletions client/package.json → client/analytics/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
],
"version": "6.3.0",
"license": "MIT",
"main": "./dist/analytics.js",
"types": "./dist/analytics.d.ts",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"scripts": {
"build": "tsc"
},
Expand Down
File renamed without changes.
141 changes: 141 additions & 0 deletions client/logpush/lib/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@

type LogEventType = 'error' | 'warn' | 'log';

interface EventItem {
type: LogEventType;
message: string;
data_dump?: object;
};

interface ClientFingerprint {
client_ip?: string | null;
client_agent?: string | null;
request_id?: string | null;
};

interface EAConfig {
remote: string;
token: string;
app_id: string;
api_name?: string;
reflectInLogs?: boolean;
};

interface EAContext {
fingerprint?: ClientFingerprint;
};

interface PushEventProps extends Omit<EventItem, 'message'> {
message: string | string[];
};

const apiPaths = {
supabase: '/rest/v1/events',
};

export class EventAggregator {

data: EventItem[] = [];
cfg: EAConfig;
ctx?: EAContext;

constructor(init: EAConfig, ctxInit?: EAContext) {
this.cfg = init;
this.ctx = ctxInit;
}

push(event: PushEventProps) {

const { type, data_dump } = event;
const message = typeof event.message === 'string' ? event.message : event.message.join('\n');

this.data.push({ type, message, data_dump });

if (this.cfg.reflectInLogs !== false) {

const consoleIO = console[event.type] || console.log;
consoleIO(event.message);

if (event.data_dump) {
console.log('Dumping data:', JSON.stringify(event.data_dump))
}
}
}

transform(type: LogEventType, args: any[]): EventItem {

// split objects and primitives
const dataParts: object[] = [];
const textParts: string[] = args.map(item => {
switch (typeof item) {
case 'string': return item;
case 'object': {
dataParts.push(item);
return dataParts.length > 1 ? `[object dump #${dataParts.length - 1}]` : '[object dumped]';
};
default: return item?.toString?.();
}
});

const message = textParts.filter(item => item.length).join(' ');
const data_dump = dataParts.length > 0 ? (dataParts.length > 1 ? dataParts : dataParts[0]) : undefined;

return { type, message, data_dump };
}

log(...data: any[]) {
this.push(this.transform('log', [...arguments]));
}

warn(...data: any[]) {
this.push(this.transform('warn', [...arguments]));
}

error(...data: any[]) {
this.push(this.transform('error', [...arguments]));
}

async flush() {

if (!this.data.length) return;

interface InsertRowItem extends EventItem, ClientFingerprint {
app_id: string;
api?: string;
};

const payload: InsertRowItem[] = this.data.map(item => Object.assign({
app_id: this.cfg.app_id,
api: this.cfg.api_name
}, item, this.ctx?.fingerprint));

try {

const remoteUrl = new URL(this.cfg.remote);
remoteUrl.pathname = apiPaths.supabase;
remoteUrl.search = '';

const response = await fetch(remoteUrl, {
method: 'POST',
headers: {
apikey: this.cfg.token,
'content-type': 'application/json'
},
body: JSON.stringify(payload)
});

if (!response.ok) {
const responseText = await response.text();
const isMeaningful = /[\w\d\"]+/.test(responseText);
throw new Error(isMeaningful ? responseText : `http: ${response.status}`);
}

this.data = [];
console.log('Flushed events successfully');

} catch (error) {
console.error('Failed to flush logpush events:', (error as Error | null)?.message || JSON.stringify(error));
}

}
};
18 changes: 18 additions & 0 deletions client/logpush/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"type": "module",
"name": "@maddsua/logpush-client",
"description": "Client for remote logging service",
"version": "2.1.0",
"license": "MIT",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"scripts": {
"build": "tsc"
},
"files": [
"dist"
],
"devDependencies": {
"typescript": "^5.3.2"
}
}
9 changes: 9 additions & 0 deletions client/logpush/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"compilerOptions": {
"lib": ["DOM", "ESNext"],
"target": "ES2017",
"outDir": "dist",
"declaration": true,
"strict": true
}
}

0 comments on commit c6fd6db

Please sign in to comment.