Skip to content

Commit

Permalink
V1.3.4
Browse files Browse the repository at this point in the history
- Introducing logging
- Enhanced caching
- Minor UI change on add server
  • Loading branch information
fakoua committed Mar 7, 2024
1 parent 4003596 commit b68facb
Show file tree
Hide file tree
Showing 17 changed files with 5,523 additions and 5,342 deletions.
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,17 @@ Or
deno run -A --reload https://deno.land/x/denoman/mod.ts
```

For logging:

```
deno run -A jsr:@fakoua/denoman --log-request --level=debug
```

- **--log-request**: to trace all the requests on the console (recommended for
debuging)
- **--level**: to log the actions and functions (debug, info, warn, error,
critical). default is 'info'

## Screenshots

![DenoMan Dashboard](https://github.com/fakoua/denoman/blob/main/resources/ss01.png?raw=true)
Expand Down
12 changes: 9 additions & 3 deletions build-tools/binToTs.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,25 @@
import { join } from "@std/path";
import { copy } from "@std/fs";
import * as log from "@std/log";

import { bin, version } from "../wwwzip/ui.ts";
import { zipDecompress } from "./zip.ts";

export async function initServer(wwwRoot: string): Promise<boolean> {
try {
log.getLogger().info("Initializing server...");
const indexFile = join(wwwRoot, "index.html");
const isExist = await exists(indexFile);
if (isExist) {
//Check for update
const installedVersion = await getUiVersion(indexFile);

if (installedVersion === version) {
return true;
}

console.log(`Updating UI from V${installedVersion} to V${version}`);
log.getLogger().info(
`Updating UI from V${installedVersion} to V${version}`,
);
//We need to remove old version
await Deno.remove(indexFile);
await Deno.remove(join(wwwRoot, "favicon.ico"));
Expand Down Expand Up @@ -46,7 +49,7 @@ export async function initServer(wwwRoot: string): Promise<boolean> {
await Deno.remove(spa, { recursive: true });
return true;
} catch (err) {
console.log(err);
log.getLogger().error(err);
return false;
}
}
Expand All @@ -62,6 +65,7 @@ export async function initServer(wwwRoot: string): Promise<boolean> {
* @returns {*}
*/
export async function zipToTs(path: string, fileName: string) {
log.getLogger().info(`Converting ${fileName}.zip to ${fileName}.ts`);
const version = await getUiVersion(join(path, `spa\\index.html`));

const binPath = join(path, `${fileName}.zip`);
Expand Down Expand Up @@ -97,6 +101,7 @@ export const bin=\`${base64}\``;
* @returns {Promise<string>}
*/
export async function tsToZip(wwwRoot: string): Promise<string> {
log.getLogger().info("Converting ts to zip");
const binContent = atob(bin);
const binArray = new Uint8Array(binContent.length);

Expand All @@ -111,6 +116,7 @@ export async function tsToZip(wwwRoot: string): Promise<string> {
}

async function getUiVersion(indexFile: string): Promise<string> {
log.getLogger().info("Getting UI version");
const content = await Deno.readTextFile(indexFile);
const regEx = /content="DenoMan\s(.*?)">/gm;
const matches = content.matchAll(regEx);
Expand Down
3 changes: 2 additions & 1 deletion deno.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@fakoua/denoman",
"version": "1.3.3",
"version": "1.3.4",
"exports": "./mod.ts",

"tasks": {
Expand All @@ -25,6 +25,7 @@
"@std/async": "jsr:@std/async@^0.218.2",
"@std/cli": "jsr:@std/cli@^0.218.2",
"@std/fs": "jsr:@std/fs@^0.218.2",
"@std/log": "jsr:@std/log@^0.218.2",
"@std/path": "jsr:@std/path@^0.218.2"
},
"importMap": "./vendor/import_map.json"
Expand Down
2 changes: 2 additions & 0 deletions deno.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

111 changes: 62 additions & 49 deletions mod.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { join } from "@std/path";
import { ensureDir, exists } from "@std/fs";
import { Application, Router } from "@oak/oak";
import { parseArgs } from "@std/cli";

import { Application, Router, RouterContext } from "@oak/oak";

import * as logging from "./src/logging.ts";
import { oakCors } from "./vendor/deno.land/x/cors@v1.2.2/mod.ts";

import { actions, getDependsServices, getServices } from "./src/services.ts";
import { getProcesses } from "./src/processes.ts";
import {
Expand All @@ -17,6 +17,7 @@ import {
import { executeCommand } from "./src/command.ts";
import * as cache from "./src/memcache.ts";
import {
ContextApiName,
DependenciesModel,
GroupModel,
ServiceModel,
Expand All @@ -25,24 +26,34 @@ import {
WinRMPayload,
} from "./src/models.ts";
import { initServer } from "./build-tools/binToTs.ts";
import { LevelName } from "jsr:@std/log@^0.218.2/levels";

const flags = parseArgs(Deno.args, {
boolean: ["log-request"],
string: ["level"],
default: { "log-request": false, level: "INFO" },
});

let logLevel = flags.level.toUpperCase();

if (
!(logLevel === "NOTSET" || logLevel === "DEBUG" || logLevel === "INFO" ||
logLevel === "WARN" || logLevel === "ERROR" || logLevel === "CRITICAL")
) {
logLevel = "INFO";
}

type ContextApiName = RouterContext<
"/api/:apiName",
{
apiName: string;
} & Record<string | number, string | undefined>,
// NOSONAR
// deno-lint-ignore no-explicit-any
Record<string, any>
>;
logging.initLogger(logLevel as LevelName, flags["log-request"]);

logging.info("Starting server...");

await initServer(await getWwwRoot());

const router = new Router();

router.get("/api/exit", (ctx) => {
ctx.response.body = true;
console.log("Exiting...");
logging.info("Exiting...");
setTimeout(() => {
Deno.exit(0);
}, 200);
Expand Down Expand Up @@ -121,6 +132,11 @@ router.post("/api/command", async (ctx) => {
const app = new Application();
let wwwRoot: string | undefined = undefined;

app.use(async (ctx, next) => {
await next();
logging.logRequest(`${ctx.request.method} ${ctx.request.url.pathname}`);
});

app.use(oakCors()); // Enable CORS for All Routes
app.use(router.allowedMethods());
app.use(router.routes());
Expand All @@ -139,40 +155,39 @@ app.use(async (context, next) => {
}
});

console.log("Listening to http://localhost:8001");
logging.info("Listening to http://localhost:8001");
logging.info("Press Ctrl+C to exit...");

await app.listen({ port: 8001 });

async function handleService(ctx: ContextApiName, payload: WinRMPayload) {
let services: ServiceModel[];
if (cache.has(`${payload.hostname}-services`)) {
services = cache.get(`${payload.hostname}-services`)!;
} else {
services = await getServices(payload);
cache.put(`${payload.hostname}-services`, services);
}
const services = await cache.getObject<ServiceModel[]>(
`${payload.hostname}-services`,
async () => {
return await getServices(payload);
},
);

ctx.response.body = services;
}

async function handleDependencies(ctx: ContextApiName, payload: WinRMPayload) {
let deps: Array<DependenciesModel>;
if (cache.has(`${payload.hostname}-dependencies`)) {
deps = cache.get(`${payload.hostname}-dependencies`)!;
} else {
deps = await getDependsServices(payload);
cache.put(`${payload.hostname}-dependencies`, deps);
}
const deps = await cache.getObject<DependenciesModel[]>(
`${payload.hostname}-dependencies`,
async () => {
return await getDependsServices(payload);
},
);
ctx.response.body = deps;
}

async function handleSystem(ctx: ContextApiName, payload: WinRMPayload) {
let system: SystemModel;
if (cache.has(`${payload.hostname}-system-info`)) {
system = cache.get(`${payload.hostname}-system-info`)!;
} else {
system = await getSystem(payload);
cache.put(`${payload.hostname}-system-info`, system);
}
const system = await cache.getObject<SystemModel>(
`${payload.hostname}-system-info`,
async () => {
return await getSystem(payload);
},
);
ctx.response.body = system;
}

Expand All @@ -192,24 +207,22 @@ async function handleDevice(ctx: ContextApiName, payload: WinRMPayload) {
}

async function handleUsers(ctx: ContextApiName, payload: WinRMPayload) {
let users: UserModel[];
if (cache.has(`${payload.hostname}-users`)) {
users = cache.get(`${payload.hostname}-users`)!;
} else {
users = await getUsers(payload);
cache.put(`${payload.hostname}-users`, users);
}
const users = await cache.getObject<UserModel[]>(
`${payload.hostname}-users`,
async () => {
return await getUsers(payload);
},
);
ctx.response.body = users;
}

async function handleGroups(ctx: ContextApiName, payload: WinRMPayload) {
let groups: GroupModel[];
if (cache.has(`${payload.hostname}-groups`)) {
groups = cache.get(`${payload.hostname}-groups`)!;
} else {
groups = await getGroups(payload);
cache.put(`${payload.hostname}-groups`, groups);
}
const groups = await cache.getObject<GroupModel[]>(
`${payload.hostname}-groups`,
async () => {
return await getGroups(payload);
},
);
ctx.response.body = groups;
}

Expand Down
11 changes: 5 additions & 6 deletions prepare-spa.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { parseArgs } from "@std/cli";

import * as log from "@std/log";
import { zipToTs } from "./build-tools/binToTs.ts";
import { zipCompress } from "./build-tools/zip.ts";

Expand All @@ -8,7 +8,6 @@ const flags = parseArgs(Deno.args, {
});

const action = flags.action;
console.log("Action:", flags);
if (action === "set-version") {
const version = flags.version || "0.0.1";
await increaseUiVersion(version);
Expand All @@ -29,17 +28,17 @@ async function increaseUiVersion(version: string) {
packageJson = JSON.stringify(pkg, null, 2);

await Deno.writeTextFile(packageFile, packageJson);
console.log("package.json file updated.");
log.getLogger().info("package.json file updated.");
}

async function spaToTypeScript() {
console.log("Compressing [q-manui/dist/spa] ...");
log.getLogger().info("Compressing [q-manui/dist/spa] ...");
await zipCompress("./q-manui/dist/spa", "./q-manui/dist/ui.zip", {
overwrite: true,
flags: [],
});

console.log("Converting [q-manui/dist/ui.zip] to [ui.ts]");
log.getLogger().info("Converting [q-manui/dist/ui.zip] to [ui.ts]");
await zipToTs("./q-manui/dist", "ui");
console.log("[ui.ts] created.");
log.getLogger().info("[ui.ts] created.");
}
4 changes: 2 additions & 2 deletions q-manui/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "q-manui",
"version": "1.3.3",
"description": "DenoMan 1.3.3",
"version": "1.3.4",
"description": "DenoMan 1.3.4",
"productName": "DenoMan",
"author": "Sameh Fakoua <s.fakoua@gmail.com>",
"private": true,
Expand Down
Loading

0 comments on commit b68facb

Please sign in to comment.