Skip to content

Commit 7a8687c

Browse files
committed
doc: ai generated comments
1 parent 2dfeeed commit 7a8687c

11 files changed

+547
-0
lines changed

src/backend/src/services/AnomalyService.js

+28
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// METADATA // {"ai-commented":{"service":"openai-completion","model":"gpt-4o"}}
12
/*
23
* Copyright (C) 2024 Puter Technologies Inc.
34
*
@@ -18,9 +19,26 @@
1819
*/
1920
const BaseService = require("./BaseService");
2021

22+
// Symbol used to indicate a denial of service instruction in anomaly handling.
2123
const DENY_SERVICE_INSTRUCTION = Symbol('DENY_SERVICE_INSTRUCTION');
2224

25+
26+
/**
27+
* @class AnomalyService
28+
* @extends BaseService
29+
* @description The AnomalyService class is responsible for managing and processing anomaly detection types and configurations.
30+
* It allows the registration of different types with associated handlers, enabling the detection of anomalies based on specified criteria.
31+
*/
2332
class AnomalyService extends BaseService {
33+
/**
34+
* AnomalyService class that extends BaseService and provides methods
35+
* for registering anomaly types and handling incoming data for those anomalies.
36+
*
37+
* The register method allows the registration of different anomaly types
38+
* and their respective configurations, including custom handlers for data
39+
* evaluation. It supports two modes of operation: a direct handler or
40+
* a threshold-based evaluation.
41+
*/
2442
_construct () {
2543
this.types = {};
2644
}
@@ -39,6 +57,16 @@ class AnomalyService extends BaseService {
3957
}
4058
this.types[type] = type_instance;
4159
}
60+
/**
61+
* Registers a new type with the service, including its configuration and handler.
62+
*
63+
* @param {string} type - The name of the type to register.
64+
* @param {Object} config - The configuration object for the type.
65+
* @param {Function} [config.handler] - An optional handler function for the type.
66+
* @param {number} [config.high] - An optional threshold value; triggers the handler if exceeded.
67+
*
68+
* @returns {void}
69+
*/
4270
async note (id, data) {
4371
const type = this.types[id];
4472
if ( ! type ) return;

src/backend/src/services/AppInformationService.js

+134
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// METADATA // {"ai-commented":{"service":"xai"}}
12
/*
23
* Copyright (C) 2024 Puter Technologies Inc.
34
*
@@ -23,6 +24,17 @@ const { DB_READ } = require("./database/consts");
2324

2425
const uuidv4 = require('uuid').v4;
2526

27+
28+
/**
29+
* @class AppInformationService
30+
* @description
31+
* The AppInformationService class manages application-related information,
32+
* including caching, statistical data, and tags for applications within the Puter ecosystem.
33+
* It provides methods for refreshing application data, managing app statistics,
34+
* and handling tags associated with apps. This service is crucial for maintaining
35+
* up-to-date information about applications, facilitating features like app listings,
36+
* recent apps, and tag-based app discovery.
37+
*/
2638
class AppInformationService {
2739
constructor ({ services }) {
2840
this.services = services;
@@ -37,33 +49,87 @@ class AppInformationService {
3749
// await new Promise(rslv => setTimeout(rslv, 500))
3850

3951
await this._refresh_app_cache();
52+
/**
53+
* Refreshes the application cache by querying the database for all apps and updating the key-value store.
54+
*
55+
* This method is called periodically to ensure that the in-memory cache reflects the latest
56+
* state from the database. It uses the 'database' service to fetch app data and then updates
57+
* multiple cache entries for quick lookups by name, ID, and UID.
58+
*
59+
* @async
60+
*/
4061
asyncSafeSetInterval(async () => {
4162
this._refresh_app_cache();
4263
}, 30 * 1000);
4364

4465
await this._refresh_app_stats();
66+
/**
67+
* Refreshes the cache of recently opened apps.
68+
* This method updates the 'recent' collection with the UIDs of apps sorted by their most recent timestamp.
69+
*
70+
* @async
71+
* @returns {Promise<void>} A promise that resolves when the cache has been refreshed.
72+
*/
4573
asyncSafeSetInterval(async () => {
4674
this._refresh_app_stats();
4775
}, 120 * 1000);
4876

4977
// This stat is more expensive so we don't update it as often
5078
await this._refresh_app_stat_referrals();
79+
/**
80+
* Refreshes the app referral statistics.
81+
* This method is computationally expensive and thus runs less frequently.
82+
* It queries the database for user counts referred by each app's origin URL.
83+
*
84+
* @async
85+
*/
5186
asyncSafeSetInterval(async () => {
5287
this._refresh_app_stat_referrals();
5388
}, 15 * MINUTE);
5489

5590
await this._refresh_recent_cache();
91+
/**
92+
* Refreshes the recent cache by updating the list of recently added or updated apps.
93+
* This method fetches all app data, filters for approved apps, sorts them by timestamp,
94+
* and updates the `this.collections.recent` array with the UIDs of the most recent 50 apps.
95+
*
96+
* @async
97+
* @private
98+
*/
5699
asyncSafeSetInterval(async () => {
57100
this._refresh_recent_cache();
58101
}, 120 * 1000);
59102

60103
await this._refresh_tags();
104+
/**
105+
* Refreshes the tags cache by iterating through all approved apps,
106+
* extracting their tags, and organizing them into a structured format.
107+
* This method updates the `this.tags` object with the latest tag information.
108+
*
109+
* @async
110+
* @method
111+
* @memberof AppInformationService
112+
*/
61113
asyncSafeSetInterval(async () => {
62114
this._refresh_tags();
63115
} , 120 * 1000);
64116
})();
65117
}
66118

119+
120+
/**
121+
* Retrieves and returns statistical data for a specific application.
122+
*
123+
* This method fetches various metrics such as the number of times the app has been opened,
124+
* the count of unique users who have opened the app, and the number of referrals attributed to the app.
125+
* It uses cached data where available to improve performance.
126+
*
127+
* @param {string} app_uid - The unique identifier for the application.
128+
* @returns {Promise<Object>} An object containing:
129+
* - {number} open_count - The total number of times the app has been opened.
130+
* - {number} user_count - The count of unique users who have opened the app.
131+
* - {number|null} referral_count - The number of referrals, or null if the data is not available or too expensive to retrieve.
132+
*/
67133
async get_stats (app_uid) {
68134
const db = this.services.get('database').get(DB_READ, 'apps');
69135

@@ -100,6 +166,19 @@ class AppInformationService {
100166
};
101167
}
102168

169+
170+
/**
171+
* Retrieves various statistics for a given app.
172+
*
173+
* This method fetches the open count, user count, and referral count for an app identified by its UID.
174+
* It uses cached values where available to improve performance, but will query the database if necessary.
175+
*
176+
* @param {string} app_uid - The unique identifier of the app for which to retrieve stats.
177+
* @returns {Promise<Object>} An object containing:
178+
* - {number} open_count - Total number of times the app was opened.
179+
* - {number} user_count - Number of unique users who opened the app.
180+
* - {number|null} referral_count - Number of referrals attributed to the app. This value might not be reported if not cached.
181+
*/
103182
async _refresh_app_cache () {
104183
this.log.tick('refresh app cache');
105184

@@ -114,6 +193,17 @@ class AppInformationService {
114193
}
115194
}
116195

196+
197+
/**
198+
* Refreshes the application cache by querying the database for all apps and updating the key-value store.
199+
*
200+
* @async
201+
* @returns {Promise<void>} A promise that resolves when the cache refresh operation is complete.
202+
*
203+
* @notes
204+
* - This method logs a tick event for performance monitoring.
205+
* - It populates the cache with app data indexed by name, id, and uid.
206+
*/
117207
async _refresh_app_stats () {
118208
this.log.tick('refresh app stats');
119209

@@ -144,6 +234,13 @@ class AppInformationService {
144234
}
145235
}
146236

237+
238+
/**
239+
* Refreshes the cache of app statistics including open and user counts.
240+
* This method updates the cache every 120 seconds to ensure data freshness.
241+
*
242+
* @async
243+
*/
147244
async _refresh_app_stat_referrals () {
148245
this.log.tick('refresh app stat referrals');
149246

@@ -176,6 +273,17 @@ class AppInformationService {
176273
this.log.info('DONE refresh app stat referrals');
177274
}
178275

276+
277+
/**
278+
* Updates the cache with recently updated apps.
279+
*
280+
* @description This method refreshes the cache containing the most recently updated applications.
281+
* It fetches all app UIDs, retrieves the corresponding app data, filters for approved apps,
282+
* sorts them by timestamp in descending order, and updates the 'recent' collection with
283+
* the UIDs of the top 50 most recent apps.
284+
*
285+
* @returns {Promise<void>} Resolves when the cache has been updated.
286+
*/
179287
async _refresh_recent_cache () {
180288
const app_keys = kv.keys(`apps:uid:*`);
181289
// console.log('APP KEYS', app_keys);
@@ -194,6 +302,16 @@ class AppInformationService {
194302
this.collections.recent = apps.map(app => app.uid).slice(0, 50);
195303
}
196304

305+
306+
/**
307+
* Refreshes the cache of recently added or updated apps.
308+
*
309+
* This method retrieves all apps from the cache, filters for approved listings,
310+
* sorts them by timestamp in descending order, and updates the `recent` collection
311+
* with the UIDs of the most recent 50 apps.
312+
*
313+
* @returns {Promise<void>}
314+
*/
197315
async _refresh_tags () {
198316
const app_keys = kv.keys(`apps:uid:*`);
199317
// console.log('APP KEYS', app_keys);
@@ -229,6 +347,22 @@ class AppInformationService {
229347
this.tags = new_tags;
230348
}
231349

350+
351+
/**
352+
* Deletes an application from the system.
353+
*
354+
* This method performs the following actions:
355+
* - Retrieves the app data from cache or database if not provided.
356+
* - Deletes the app record from the database.
357+
* - Removes the app from all relevant caches (by name, id, and uid).
358+
* - Removes the app from the recent collection if present.
359+
* - Removes the app from any associated tags.
360+
*
361+
* @param {string} app_uid - The unique identifier of the app to be deleted.
362+
* @param {Object} [app] - The app object, if already fetched. If not provided, it will be retrieved.
363+
* @throws {Error} If the app is not found in either cache or database.
364+
* @returns {Promise<void>} A promise that resolves when the app has been successfully deleted.
365+
*/
232366
async delete_app (app_uid, app) {
233367
const db = this.services.get('database').get(DB_READ, 'apps');
234368

src/backend/src/services/BaseService.js

+46
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// METADATA // {"ai-params":{"service":"xai"},"ai-refs":["../../doc/contributors/boot-sequence.md"],"ai-commented":{"service":"xai"}}
12
/*
23
* Copyright (C) 2024 Puter Technologies Inc.
34
*
@@ -18,8 +19,25 @@
1819
*/
1920
const { concepts } = require("@heyputer/putility");
2021

22+
23+
24+
// This is a no-op function that AI is incapable of writing a comment for.
25+
// That said, I suppose it didn't need one anyway.
2126
const NOOP = async () => {};
2227

28+
29+
/**
30+
* @class BaseService
31+
* @extends concepts.Service
32+
* @description
33+
* BaseService is the foundational class for all services in the Puter backend.
34+
* It provides lifecycle methods like `construct` and `init` that are invoked during
35+
* different phases of the boot sequence. This class ensures that services can be
36+
* instantiated, initialized, and activated in a coordinated manner through
37+
* events emitted by the Kernel. It also manages common service resources like
38+
* logging and error handling, and supports legacy services by allowing
39+
* instantiation after initialization but before consolidation.
40+
*/
2341
class BaseService extends concepts.Service {
2442
constructor (service_resources, ...a) {
2543
const { services, config, my_config, name, args } = service_resources;
@@ -36,10 +54,29 @@ class BaseService extends concepts.Service {
3654
}
3755
}
3856

57+
58+
/**
59+
* Initializes the service with configuration and dependencies.
60+
* This method sets up logging and error handling, and calls a custom `_init` method if defined.
61+
*
62+
* @param {Object} args - Arguments passed to the service for initialization.
63+
* @returns {Promise<void>} A promise that resolves when initialization is complete.
64+
*/
3965
async construct () {
4066
await (this._construct || NOOP).call(this, this.args);
4167
}
4268

69+
70+
/**
71+
* Performs the initialization phase of the service lifecycle.
72+
* This method sets up logging and error handling for the service,
73+
* then calls the service-specific initialization logic if defined.
74+
*
75+
* @async
76+
* @memberof BaseService
77+
* @instance
78+
* @returns {Promise<void>} A promise that resolves when initialization is complete.
79+
*/
4380
async init () {
4481
const services = this.services;
4582
this.log = services.get('log-service').create(this.service_name);
@@ -48,6 +85,15 @@ class BaseService extends concepts.Service {
4885
await (this._init || NOOP).call(this, this.args);
4986
}
5087

88+
89+
/**
90+
* Handles an event by retrieving the appropriate event handler
91+
* and executing it with the provided arguments.
92+
*
93+
* @param {string} id - The identifier of the event to handle.
94+
* @param {Array<any>} args - The arguments to pass to the event handler.
95+
* @returns {Promise<any>} The result of the event handler execution.
96+
*/
5197
async __on (id, args) {
5298
const handler = this.__get_event_handler(id);
5399

src/backend/src/services/BootScriptService.js

+30
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,29 @@
1+
// METADATA // {"ai-commented":{"service":"mistral","model":"mistral-large-latest"}}
12
const { Context } = require("../util/context");
23
const BaseService = require("./BaseService");
34

5+
6+
/**
7+
* @class BootScriptService
8+
* @extends BaseService
9+
* @description The BootScriptService class extends BaseService and is responsible for
10+
* managing and executing boot scripts. It provides methods to handle boot scripts when
11+
* the system is ready and to run individual script commands.
12+
*/
413
class BootScriptService extends BaseService {
514
static MODULES = {
615
fs: require('fs'),
716
}
17+
/**
18+
* Loads and executes a boot script if specified in the arguments.
19+
*
20+
* This method reads the provided boot script file, parses it, and runs the script using the `run_script` method.
21+
* If no boot script is specified in the arguments, the method returns immediately.
22+
*
23+
* @async
24+
* @function
25+
* @returns {Promise<void>}
26+
*/
827
async ['__on_boot.ready'] () {
928
const args = Context.get('args');
1029
if ( ! args['boot-script'] ) return;
@@ -17,6 +36,17 @@ class BootScriptService extends BaseService {
1736
await this.run_script(boot_json);
1837
}
1938

39+
40+
/**
41+
* Executes a series of commands defined in a JSON boot script.
42+
*
43+
* This method processes each command in the boot_json array.
44+
* If the command is recognized within the predefined scope, it will be executed.
45+
* If not, an error is thrown.
46+
*
47+
* @param {Array} boot_json - An array of commands to execute.
48+
* @throws {Error} Thrown if an unknown command is encountered.
49+
*/
2050
async run_script (boot_json) {
2151
const scope = {
2252
runner: 'boot-script',

0 commit comments

Comments
 (0)