|
| 1 | +/********************************************************************** |
| 2 | + * Copyright (C) 2024 Red Hat, Inc. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + * |
| 16 | + * SPDX-License-Identifier: Apache-2.0 |
| 17 | + ***********************************************************************/ |
| 18 | + |
| 19 | +import type { Disposable } from '@podman-desktop/api'; |
| 20 | +import type { Request, Response } from 'express'; |
| 21 | +import express from 'express'; |
| 22 | +import type { Server } from 'http'; |
| 23 | +import path from 'node:path'; |
| 24 | +import http from 'node:http'; |
| 25 | +import { existsSync } from 'fs'; |
| 26 | +import { getFreeRandomPort } from '../utils/ports'; |
| 27 | +import * as podmanDesktopApi from '@podman-desktop/api'; |
| 28 | +import { readFile } from 'fs/promises'; |
| 29 | + |
| 30 | +const DEFAULT_PORT = 10434; |
| 31 | +const SHOW_API_INFO_COMMAND = 'ai-lab.show-api-info'; |
| 32 | + |
| 33 | +export class ApiServer implements Disposable { |
| 34 | + #listener?: Server; |
| 35 | + |
| 36 | + constructor(private extensionContext: podmanDesktopApi.ExtensionContext) {} |
| 37 | + |
| 38 | + protected getListener(): Server | undefined { |
| 39 | + return this.#listener; |
| 40 | + } |
| 41 | + |
| 42 | + async init(): Promise<void> { |
| 43 | + const app = express(); |
| 44 | + |
| 45 | + const router = express.Router(); |
| 46 | + router.use(express.json()); |
| 47 | + |
| 48 | + // declare routes |
| 49 | + router.get('/version', this.getVersion.bind(this)); |
| 50 | + app.use('/api', router); |
| 51 | + app.use('/spec', this.getSpec.bind(this)); |
| 52 | + |
| 53 | + const server = http.createServer(app); |
| 54 | + let listeningOn = DEFAULT_PORT; |
| 55 | + server.on('listening', () => { |
| 56 | + this.displayApiInfo(listeningOn); |
| 57 | + }); |
| 58 | + server.on('error', () => { |
| 59 | + getFreeRandomPort('0.0.0.0') |
| 60 | + .then((randomPort: number) => { |
| 61 | + console.warn(`port ${DEFAULT_PORT} in use, using ${randomPort} for API server`); |
| 62 | + listeningOn = randomPort; |
| 63 | + this.#listener = server.listen(randomPort); |
| 64 | + }) |
| 65 | + .catch((e: unknown) => { |
| 66 | + console.error('unable to get a free port for the api server', e); |
| 67 | + }); |
| 68 | + }); |
| 69 | + this.#listener = server.listen(DEFAULT_PORT); |
| 70 | + } |
| 71 | + |
| 72 | + displayApiInfo(port: number): void { |
| 73 | + const apiStatusBarItem = podmanDesktopApi.window.createStatusBarItem(); |
| 74 | + apiStatusBarItem.text = `AI Lab API listening on port ${port}`; |
| 75 | + apiStatusBarItem.command = SHOW_API_INFO_COMMAND; |
| 76 | + this.extensionContext.subscriptions.push( |
| 77 | + podmanDesktopApi.commands.registerCommand(SHOW_API_INFO_COMMAND, async () => { |
| 78 | + const address = `http://localhost:${port}`; |
| 79 | + const result = await podmanDesktopApi.window.showInformationMessage( |
| 80 | + `AI Lab API is listening on\n${address}`, |
| 81 | + 'OK', |
| 82 | + `Copy`, |
| 83 | + ); |
| 84 | + if (result === 'Copy') { |
| 85 | + await podmanDesktopApi.env.clipboard.writeText(address); |
| 86 | + } |
| 87 | + }), |
| 88 | + apiStatusBarItem, |
| 89 | + ); |
| 90 | + apiStatusBarItem.show(); |
| 91 | + } |
| 92 | + |
| 93 | + private getFile(filepath: string): string { |
| 94 | + // when plugin is installed, the file is placed in the plugin directory (~/.local/share/containers/podman-desktop/plugins/<pluginname>/) |
| 95 | + const prodFile = path.join(__dirname, filepath); |
| 96 | + if (existsSync(prodFile)) { |
| 97 | + return prodFile; |
| 98 | + } |
| 99 | + // return dev file |
| 100 | + return path.join(__dirname, '..', '..', filepath); |
| 101 | + } |
| 102 | + |
| 103 | + getSpecFile(): string { |
| 104 | + return this.getFile('../api/openapi.yaml'); |
| 105 | + } |
| 106 | + |
| 107 | + getPackageFile(): string { |
| 108 | + return this.getFile('../package.json'); |
| 109 | + } |
| 110 | + |
| 111 | + dispose(): void { |
| 112 | + this.#listener?.close(); |
| 113 | + } |
| 114 | + |
| 115 | + getSpec(_req: Request, res: Response): void { |
| 116 | + const doErr = (err: unknown) => { |
| 117 | + res.status(500).json({ |
| 118 | + message: 'unable to get spec', |
| 119 | + errors: [err], |
| 120 | + }); |
| 121 | + }; |
| 122 | + try { |
| 123 | + const spec = this.getSpecFile(); |
| 124 | + readFile(spec, 'utf-8') |
| 125 | + .then(content => { |
| 126 | + res.status(200).type('application/yaml').send(content); |
| 127 | + }) |
| 128 | + .catch((err: unknown) => doErr(err)); |
| 129 | + } catch (err: unknown) { |
| 130 | + doErr(err); |
| 131 | + } |
| 132 | + } |
| 133 | + |
| 134 | + getVersion(_req: Request, res: Response): void { |
| 135 | + const doErr = (err: unknown) => { |
| 136 | + res.status(500).json({ |
| 137 | + message: 'unable to get version', |
| 138 | + errors: [err], |
| 139 | + }); |
| 140 | + }; |
| 141 | + try { |
| 142 | + const pkg = this.getPackageFile(); |
| 143 | + readFile(pkg, 'utf-8') |
| 144 | + .then(content => { |
| 145 | + const json = JSON.parse(content); |
| 146 | + res.status(200).json({ version: `v${json.version}` }); |
| 147 | + }) |
| 148 | + .catch((err: unknown) => doErr(err)); |
| 149 | + } catch (err: unknown) { |
| 150 | + doErr(err); |
| 151 | + } |
| 152 | + } |
| 153 | +} |
0 commit comments