fix: use global logger for extensions

fixes #91
This commit is contained in:
Ash Keel 2023-11-05 12:47:04 +01:00
parent 281205cd08
commit 5cda8de70c
No known key found for this signature in database
GPG Key ID: 53A9E9A6035DD109
10 changed files with 146 additions and 50 deletions

39
app.go
View File

@ -8,7 +8,7 @@ import (
"io"
"log"
"mime/multipart"
nethttp "net/http"
"net/http"
"os"
"runtime/debug"
"strconv"
@ -21,6 +21,7 @@ import (
"github.com/urfave/cli/v2"
"github.com/wailsapp/wails/v2/pkg/runtime"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"github.com/strimertul/strimertul/database"
"github.com/strimertul/strimertul/docs"
@ -38,6 +39,7 @@ type App struct {
ready *sync.RWSync[bool]
isFatalError *sync.RWSync[bool]
backupOptions database.BackupOptions
cancelLogs database.CancelFunc
db *database.LocalDBClient
twitchManager *twitch.Manager
@ -107,13 +109,14 @@ func (a *App) startup(ctx context.Context) {
}
// Set meta keys
_ = a.db.PutKey("stul-meta/version", appVersion)
_ = a.db.PutKey("strimertul/version", appVersion)
a.ready.Set(true)
runtime.EventsEmit(ctx, "ready", true)
logger.Info("Strimertul is ready")
// Start redirecting logs to UI
// Add logs I/O to UI
_, a.cancelLogs = a.listenForLogs()
go a.forwardLogs()
// Run HTTP server
@ -173,6 +176,29 @@ func (a *App) initializeComponents() error {
return nil
}
type ExternalLog struct {
Level string `json:"level"`
Message string `json:"message"`
Data map[string]any `json:"data"`
}
func (a *App) listenForLogs() (error, database.CancelFunc) {
return a.db.SubscribeKey("strimertul/@log", func(newValue string) {
var entry ExternalLog
if err := json.Unmarshal([]byte(newValue), &entry); err != nil {
return
}
level, err := zapcore.ParseLevel(entry.Level)
if err != nil {
level = zapcore.InfoLevel
}
fields := parseAsFields(entry.Data)
logger.Log(level, entry.Message, fields...)
})
}
func (a *App) forwardLogs() {
for entry := range incomingLogs {
runtime.EventsEmit(a.ctx, "log-event", entry)
@ -180,6 +206,9 @@ func (a *App) forwardLogs() {
}
func (a *App) stop(context.Context) {
if a.cancelLogs != nil {
a.cancelLogs()
}
if a.lock != nil {
warnOnError(a.lock.Unlock(), "Could not remove lock file")
}
@ -260,14 +289,14 @@ func (a *App) SendCrashReport(errorData string, info string) (string, error) {
return "", err
}
resp, err := nethttp.Post(crashReportURL, w.FormDataContentType(), &b)
resp, err := http.Post(crashReportURL, w.FormDataContentType(), &b)
if err != nil {
logger.Error("Could not send crash report", zap.Error(err))
return "", err
}
// Check the response
if resp.StatusCode != nethttp.StatusOK {
if resp.StatusCode != http.StatusOK {
byt, _ := io.ReadAll(resp.Body)
logger.Error("Crash report server returned error", zap.String("status", resp.Status), zap.String("response", string(byt)))
return "", fmt.Errorf("crash report server returned error: %s - %s", resp.Status, string(byt))

View File

@ -46,6 +46,7 @@ export class Extension extends EventTarget {
kind: 'arguments',
source: info.source,
options: runOptions,
name: info.name,
dependencies,
});
}
@ -64,13 +65,10 @@ export class Extension extends EventTarget {
if (msg.error instanceof Error) {
this.workerError = msg.error;
} else {
this.workerError = new Error(msg.error.toString());
this.workerError = new Error(JSON.stringify(msg.error));
}
this.status = ExtensionStatus.Error;
break;
case 'log':
this.dispatchEvent(new CustomEvent('log', { detail: msg }));
break;
}
}

View File

@ -0,0 +1,24 @@
import decodeVLQ from '../../vendor/vlq/decode';
interface SourceMap {
file: string;
version: 3;
sources: string[];
names: string[];
mappings: string;
sourceRoot: string;
}
export type SourceMapMappings = [number, number, number, number][][];
export function parseSourceMap(sourceMapText: string): SourceMapMappings {
const sourceMap = JSON.parse(sourceMapText) as SourceMap;
return sourceMap.mappings
.split(';')
.map((m) => m.split(','))
.map((line) => line.map(decodeVLQ));
}
export function mapError(error: Error, mappings: SourceMapMappings) {
/* TODO */
}

View File

@ -22,15 +22,13 @@ export enum ExtensionStatus {
}
export type ExtensionHostCommand = EHParamMessage | EHStartMessage;
export type ExtensionHostMessage =
| EHStatusChangeMessage
| EHErrorMessage
| EHLogMessage;
export type ExtensionHostMessage = EHStatusChangeMessage | EHErrorMessage;
interface EHParamMessage {
kind: 'arguments';
options: ExtensionRunOptions;
dependencies: ExtensionDependencies;
source: string;
name: string;
}
interface EHStartMessage {
kind: 'start';
@ -43,13 +41,3 @@ interface EHErrorMessage {
kind: 'error';
error: unknown;
}
interface EHLogMessage {
kind: 'log';
level: string;
message: string;
}
export interface LogMessage {
level: string;
message: string;
}

View File

@ -1,21 +1,23 @@
import Kilovolt from '@strimertul/kilovolt-client';
import * as ts from 'typescript';
import ts from 'typescript';
import {
ExtensionHostCommand,
ExtensionHostMessage,
ExtensionStatus,
} from '../types';
import { SourceMapMappings, parseSourceMap } from '../sourceMap';
const sendMessage = (
message: ExtensionHostMessage,
transfer?: Transferable[],
) => postMessage(message, transfer);
// eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-empty-function
async function ExtensionFunction(kv: Kilovolt) {}
// eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-empty-function, no-empty-function
async function ExtensionFunction(_kv: Kilovolt) {}
let extFn: typeof ExtensionFunction = null;
let kv: Kilovolt;
let name: string;
let extensionStatus = ExtensionStatus.GettingReady;
function setStatus(status: ExtensionStatus) {
@ -26,14 +28,16 @@ function setStatus(status: ExtensionStatus) {
});
}
function log(level: string) {
function log(level: string, sourceMap: SourceMapMappings) {
// eslint-disable-next-line func-names
return function (...args: { toString(): string }[]) {
const message = args.join(' ');
sendMessage({
kind: 'log',
void kv.putJSON('strimertul/@log', {
level,
message,
data: {
extension: name,
},
});
};
}
@ -61,6 +65,8 @@ onmessage = async (ev: MessageEvent<ExtensionHostCommand>) => {
const cmd = ev.data;
switch (cmd.kind) {
case 'arguments': {
name = cmd.name;
// Create Kilovolt instance
kv = new Kilovolt(cmd.dependencies.kilovolt.address, {
password: cmd.dependencies.kilovolt.password,
@ -70,14 +76,19 @@ onmessage = async (ev: MessageEvent<ExtensionHostCommand>) => {
try {
// Transpile TS into JS
const out = ts.transpileModule(cmd.source, {
compilerOptions: { module: ts.ModuleKind.ES2022 },
compilerOptions: {
module: ts.ModuleKind.ES2022,
sourceMap: true,
},
});
const sourceMap = parseSourceMap(out.sourceMapText);
// Replace console.* methods with something that logs to UI
console.log = log('info');
console.info = log('info');
console.warn = log('warn');
console.error = log('error');
console.log = log('info', sourceMap);
console.info = log('info', sourceMap);
console.warn = log('warn', sourceMap);
console.error = log('error', sourceMap);
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
extFn = ExtensionFunction.constructor('kv', out.outputText);

View File

@ -128,17 +128,6 @@ export const createExtensionInstance = createAsyncThunk<
payload.dependencies,
payload.runOptions,
);
ext.addEventListener('log', (ev: CustomEvent<LogMessage>) => {
dispatch(
loggingReducer.actions.uiLogEvent({
time: new Date(),
caller: `extensionHost/${payload.entry.name}`,
level: ev.detail.level,
message: ev.detail.message,
data: { extension: payload.entry.name },
}),
);
});
ext.addEventListener('statusChanged', (ev: CustomEvent<ExtensionStatus>) => {
dispatch(
extensionsReducer.actions.extensionStatusChanged({

View File

@ -46,9 +46,6 @@ const loggingReducer = createSlice({
receivedEvent(state, { payload }: PayloadAction<main.LogEntry>) {
state.messages.push(processEntry(payload));
},
uiLogEvent(state, { payload }: PayloadAction<ProcessedLogEntry>) {
state.messages.push(payload);
},
clearedEvents(state) {
state.messages = [];
},

View File

@ -45,7 +45,7 @@ import StrimertulPage from './pages/Strimertul';
import TwitchSettingsPage from './pages/TwitchSettings';
import UISettingsPage from './pages/UISettingsPage';
import ExtensionsPage from './pages/Extensions';
import { getTheme, lightMode, styled } from './theme';
import { getTheme, styled } from './theme';
import Loading from './components/Loading';
import InteractiveAuthDialog from './components/InteractiveAuthDialog';

60
frontend/src/vendor/vlq/decode.ts vendored Normal file
View File

@ -0,0 +1,60 @@
/* eslint-disable no-bitwise */
/*
Copyright (c) 2017-2021 [these people](https://github.com/Rich-Harris/vlq/graphs/contributors)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
const chatToInt: Record<string, number> = {};
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
.split('')
.forEach((char, i) => {
chatToInt[char] = i;
});
export default function decode(
string: string,
): [number, number, number, number] {
const result: number[] = [];
let shift = 0;
let value = 0;
for (let i = 0; i < string.length; i += 1) {
let integer = chatToInt[string[i]];
if (integer === undefined) {
throw new Error(`Invalid character (${string[i]})`);
}
const hasContinuationBit = integer & 32;
integer &= 31;
value += integer << shift;
if (hasContinuationBit) {
shift += 5;
} else {
const shouldNegate = value & 1;
value >>>= 1;
if (shouldNegate) {
result.push(value === 0 ? -0x80000000 : -value);
} else {
result.push(value);
}
// reset
value = 0;
shift = 0;
}
}
return result as [number, number, number, number];
}

View File

@ -10,7 +10,7 @@
"baseUrl": ".",
"paths": {
"@wailsapp/*": ["./wailsjs/*"],
"~/*": ["./src/*"]
"~/*": ["./src/*"],
}
}
}