mirror of
https://github.com/HeyPuter/puter.git
synced 2025-01-23 06:00:21 +08:00
doc: fix generated comment errors (batch 1)
This commit is contained in:
parent
15898fe5b7
commit
540821c759
@ -32,11 +32,6 @@ const BaseService = require("../../services/BaseService");
|
||||
* ensures that the owner of a protected app has implicit permission to access it.
|
||||
*/
|
||||
class ProtectedAppService extends BaseService {
|
||||
/**
|
||||
* Class representing a service for protected applications.
|
||||
* Extends the BaseService class to provide additional functionality specific to protected apps.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Initializes the ProtectedAppService.
|
||||
* Registers a permission rewriter and implicator to handle application-specific permissions.
|
||||
|
@ -42,8 +42,6 @@ class AlarmService extends BaseService {
|
||||
* This method initializes the AlarmService by setting up its internal data structures and initializing any required dependencies.
|
||||
*
|
||||
* It reads in the known errors from a JSON5 file and sets them as the known_errors property of the AlarmService instance.
|
||||
*
|
||||
* It also registers commands with the provided commands service.
|
||||
*/
|
||||
async _construct () {
|
||||
this.alarms = {};
|
||||
|
@ -29,15 +29,8 @@ const BaseService = require("../../services/BaseService");
|
||||
* Parameters can have constraints, default values, and change listeners.
|
||||
*/
|
||||
class ParameterService extends BaseService {
|
||||
/**
|
||||
* Parameter service for managing system-wide parameters
|
||||
* @extends BaseService
|
||||
* @class
|
||||
* @description Handles registration, storage, and access of parameters across services.
|
||||
* Parameters can be bound to instances, subscribed to for changes, and accessed via commands.
|
||||
* Each parameter has a unique service-scoped ID and optional constraints.
|
||||
*/
|
||||
_construct () {
|
||||
/** @type {Array<Parameter>} */
|
||||
this.parameters_ = [];
|
||||
}
|
||||
|
||||
@ -99,11 +92,11 @@ class ParameterService extends BaseService {
|
||||
return parameter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers parameter-related commands with the command service
|
||||
* @param {Object} commands - The command service instance to register with
|
||||
*/
|
||||
_registerCommands (commands) {
|
||||
/**
|
||||
* Registers parameter-related commands with the command service
|
||||
* @param {Object} commands - The command service instance to register with
|
||||
*/
|
||||
const completeParameterName = (args) => {
|
||||
// The parameter name is the first argument, so return no results if we're on the second or later.
|
||||
if (args.length > 1)
|
||||
|
@ -37,25 +37,27 @@ class ServerHealthService extends BaseService {
|
||||
linuxutil: 'core.util.linuxutil'
|
||||
};
|
||||
|
||||
static MODULES = {
|
||||
fs: require('fs'),
|
||||
}
|
||||
/**
|
||||
* Defines the modules used by ServerHealthService.
|
||||
* This static property is used to initialize and access system modules required for health checks.
|
||||
* @type {Object}
|
||||
* @property {fs} fs - The file system module for reading system information.
|
||||
*/
|
||||
_construct () {
|
||||
this.checks_ = [];
|
||||
this.failures_ = [];
|
||||
static MODULES = {
|
||||
fs: require('fs'),
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the internal checks and failure tracking for the service.
|
||||
* This method sets up empty arrays to store health checks and their failure statuses.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
_construct () {
|
||||
this.checks_ = [];
|
||||
this.failures_ = [];
|
||||
}
|
||||
|
||||
async _init () {
|
||||
this.init_service_checks_();
|
||||
|
||||
|
@ -30,6 +30,7 @@ const BaseService = require("../../services/BaseService");
|
||||
* in situations where ContextInitService isn't able to
|
||||
* initialize a context.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @class MountpointService
|
||||
* @extends BaseService
|
||||
|
@ -34,11 +34,7 @@ class AuthAuditService extends BaseService {
|
||||
static MODULES = {
|
||||
uuidv4: require('uuid').v4,
|
||||
}
|
||||
/**
|
||||
* Generates a unique identifier for the AuthAuditService module.
|
||||
*
|
||||
* @returns {Object} An object containing a method to generate a UUID v4.
|
||||
*/
|
||||
|
||||
async _init () {
|
||||
this.db = this.services.get('database').get(DB_WRITE, 'auth:audit');
|
||||
}
|
||||
|
@ -130,7 +130,6 @@ class EdgeRateLimitService extends BaseService {
|
||||
/**
|
||||
* Initializes the EdgeRateLimitService by setting up a periodic cleanup interval.
|
||||
* This method sets an interval that calls the cleanup function every 5 minutes.
|
||||
* It does not take any parameters and does not return any value.
|
||||
*/
|
||||
async _init () {
|
||||
asyncSafeSetInterval(() => this.cleanup(), 5 * MINUTE);
|
||||
|
@ -179,13 +179,6 @@ class IdentificationService extends BaseService {
|
||||
this.mw = new RequesterIdentificationExpressMiddleware();
|
||||
}
|
||||
/**
|
||||
* Constructor for the IdentificationService class.
|
||||
* Initializes the middleware for requester identification.
|
||||
*/
|
||||
_init () {
|
||||
this.mw.log = this.log;
|
||||
}
|
||||
/**
|
||||
* Initializes the middleware logger.
|
||||
*
|
||||
* This method sets the logger for the `RequesterIdentificationExpressMiddleware` instance.
|
||||
@ -194,6 +187,12 @@ class IdentificationService extends BaseService {
|
||||
* @method
|
||||
* @name _init
|
||||
*/
|
||||
_init () {
|
||||
this.mw.log = this.log;
|
||||
}
|
||||
/**
|
||||
* We need to listen to this event to install a context-aware middleware
|
||||
*/
|
||||
async ['__on_install.middlewares.context-aware'] (_, { app }) {
|
||||
this.mw.install(app);
|
||||
}
|
||||
|
@ -74,12 +74,6 @@ class Actor extends AdvancedBase {
|
||||
});
|
||||
}
|
||||
|
||||
constructor (o, ...a) {
|
||||
super(o, ...a);
|
||||
for ( const k in o ) {
|
||||
this[k] = o[k];
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Initializes the Actor instance with the provided parameters.
|
||||
* This constructor assigns object properties from the input object to the instance.
|
||||
@ -87,14 +81,17 @@ class Actor extends AdvancedBase {
|
||||
* @param {Object} o - The object containing actor parameters.
|
||||
* @param {...any} a - Additional arguments passed to the parent class constructor.
|
||||
*/
|
||||
constructor (o, ...a) {
|
||||
super(o, ...a);
|
||||
for ( const k in o ) {
|
||||
this[k] = o[k];
|
||||
}
|
||||
}
|
||||
|
||||
get uid () {
|
||||
return this.type.uid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a cryptographically-secure deterministic UUID
|
||||
* from an actor's UID.
|
||||
*/
|
||||
/**
|
||||
* Generates a cryptographically-secure deterministic UUID
|
||||
* from an actor's UID. The generated UUID is derived by
|
||||
@ -155,14 +152,6 @@ class ActorType {
|
||||
* and related type management.
|
||||
*/
|
||||
class SystemActorType extends ActorType {
|
||||
/**
|
||||
* Constructs a new instance of the actor type.
|
||||
*
|
||||
* @param {Object} o - The initial properties for the actor type.
|
||||
* @param {...*} a - Additional arguments to pass to the super class constructor.
|
||||
*
|
||||
* @throws {Error} If there is an issue in initializing the actor type.
|
||||
*/
|
||||
get uid () {
|
||||
return 'system';
|
||||
}
|
||||
@ -181,12 +170,6 @@ class SystemActorType extends ActorType {
|
||||
* user actors and define how they relate to other types of actors within the system.
|
||||
*/
|
||||
class UserActorType extends ActorType {
|
||||
/**
|
||||
* Constructs a new UserActorType instance.
|
||||
*
|
||||
* @param {Object} o - The initial properties to set on the instance.
|
||||
* @param {...any} a - Additional arguments to pass to the constructor.
|
||||
*/
|
||||
get uid () {
|
||||
return 'user:' + this.user.uuid;
|
||||
}
|
||||
@ -204,17 +187,6 @@ class UserActorType extends ActorType {
|
||||
* to cater to user-specific needs.
|
||||
*/
|
||||
class AppUnderUserActorType extends ActorType {
|
||||
/**
|
||||
* Create a new instance of the actor type, initializing it with the given parameters.
|
||||
*
|
||||
* This method first checks for associated user and app UIDs in the params,
|
||||
* fetching their respective data asynchronously if present. It then
|
||||
* constructs a new Actor with the provided type.
|
||||
*
|
||||
* @param {Function} type - The class constructor for the actor type.
|
||||
* @param {Object} params - Initialization parameters for the actor (optional).
|
||||
* @returns {Actor} A new instance of the Actor type.
|
||||
*/
|
||||
get uid () {
|
||||
return 'app-under-user:' + this.user.uuid + ':' + this.app.uid;
|
||||
}
|
||||
@ -240,14 +212,6 @@ class AccessTokenActorType extends ActorType {
|
||||
// authorized: an Actor who is authorized by the token
|
||||
// token: a string
|
||||
|
||||
/**
|
||||
* Constructs an instance of AccessTokenActorType.
|
||||
* This class represents an access token actor containing information
|
||||
* about the authorizer and authorized actors, as well as the token string.
|
||||
*
|
||||
* @param {Object} o - The object containing properties to initialize the access token actor.
|
||||
* @param {...*} a - Additional arguments for further initialization.
|
||||
*/
|
||||
get uid () {
|
||||
return 'access-token:' + this.authorizer.uid +
|
||||
':' + ( this.authorized?.uid ?? '<none>' ) +
|
||||
@ -274,11 +238,6 @@ class AccessTokenActorType extends ActorType {
|
||||
* pertinent to site-level operations and interactions in the actor framework.
|
||||
*/
|
||||
class SiteActorType {
|
||||
constructor (o, ...a) {
|
||||
for ( const k in o ) {
|
||||
this[k] = o[k];
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Constructor for the SiteActorType class.
|
||||
* Initializes a new instance of SiteActorType with the provided properties.
|
||||
@ -286,6 +245,12 @@ class SiteActorType {
|
||||
* @param {Object} o - The properties to initialize the SiteActorType with.
|
||||
* @param {...*} a - Additional arguments.
|
||||
*/
|
||||
constructor (o, ...a) {
|
||||
for ( const k in o ) {
|
||||
this[k] = o[k];
|
||||
}
|
||||
}
|
||||
|
||||
get uid () {
|
||||
return `site:` + this.site.name
|
||||
}
|
||||
|
@ -24,11 +24,11 @@ const BaseService = require("../BaseService");
|
||||
|
||||
|
||||
/**
|
||||
* Class representing the AntiCSRFService, which extends BaseService.
|
||||
* This service is responsible for issuing and managing anti-CSRF tokens
|
||||
* to enhance security for web requests by validating session-based tokens
|
||||
* and preventing cross-site request forgery attacks.
|
||||
*/
|
||||
* A utility class used by AntiCSRFService to manage a circular queue of
|
||||
* CSRF tokens (or, as we like to call them, "anti-CSRF" tokens).
|
||||
*
|
||||
* A token expires when it is evicted from the queue.
|
||||
*/
|
||||
class CircularQueue {
|
||||
constructor (size) {
|
||||
this.size = size;
|
||||
|
@ -44,17 +44,15 @@ class AuthService extends BaseService {
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* This method is responsible for authenticating the user based on the provided token.
|
||||
* It checks the type of the token and performs the appropriate actions to validate and retrieve the user.
|
||||
*
|
||||
* @param {string} token - The JWT token to be authenticated.
|
||||
* @returns {Promise<Actor>} A Promise that resolves with an Actor object representing the authenticated user.
|
||||
*/
|
||||
async _init () {
|
||||
this.db = await this.services.get('database').get(DB_WRITE, 'auth');
|
||||
this.svc_session = await this.services.get('session');
|
||||
|
||||
// "FPE" stands for "Format Preserving Encryption"
|
||||
// The `uuid_fpe_key` is a key for creating encrypted alternatives
|
||||
// to UUIDs and decrypting them back to the original UUIDs
|
||||
//
|
||||
// We do this to avoid exposing the internal UUID for sessions.
|
||||
const uuid_fpe_key = this.config.uuid_fpe_key
|
||||
? UUIDFPE.uuidToBuffer(this.config.uuid_fpe_key)
|
||||
: this.modules.crypto.randomBytes(16);
|
||||
@ -229,20 +227,12 @@ class AuthService extends BaseService {
|
||||
|
||||
|
||||
/**
|
||||
* Description:
|
||||
* This method is responsible for checking the session validity based on the provided token.
|
||||
* It verifies the token, retrieves the user and session information, and checks if the session is still valid.
|
||||
* If the session is valid, it returns an object containing the user and token information.
|
||||
* If the session is not valid, it returns an empty object.
|
||||
*
|
||||
* Parameters:
|
||||
* cur_token (string): The token to be checked.
|
||||
* meta (object): Optional metadata to be associated with the session.
|
||||
*
|
||||
* Return value:
|
||||
* Object: If the session is valid, it returns an object containing the user and token information. If the session is not valid, it returns an empty object.
|
||||
*/
|
||||
// This is an example of how the JSDoc comment for the method at line 206 might look like.
|
||||
* Internal method for creating a session.
|
||||
*
|
||||
* If a request object is provided in the metadata, it will be used to
|
||||
* extract information about the requestor and include it in the
|
||||
* session's metadata.
|
||||
*/
|
||||
async create_session_ (user, meta = {}) {
|
||||
this.log.info(`CREATING SESSION`);
|
||||
|
||||
@ -288,24 +278,22 @@ class AuthService extends BaseService {
|
||||
|
||||
|
||||
/**
|
||||
* This method is used to authenticate an actor using an access token. It checks if the token is valid and if the user or app associated with the token is authorized.
|
||||
*
|
||||
* @param {string} token - The access token to be authenticated.
|
||||
* @returns {Actor} The authenticated actor object.
|
||||
*/
|
||||
* Alias to SessionService's get_session method,
|
||||
* in case AuthService ever needs to wrap this functionality.
|
||||
*/
|
||||
async get_session_ (uuid) {
|
||||
return await this.svc_session.get_session(uuid);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* This method is used to authenticate a user using their access token.
|
||||
* It checks the type of the token and performs the necessary actions based on that.
|
||||
* If the token is valid and the user is authenticated, it returns an Actor object representing the user.
|
||||
* If the token is invalid or the user is not authenticated, it throws an error.
|
||||
* @param {string} token - The access token to be authenticated.
|
||||
* @returns {Actor} The Actor object representing the authenticated user.
|
||||
*/
|
||||
* Creates a session token using TokenService's sign method
|
||||
* with type 'session' using a newly created session for the
|
||||
* specified user.
|
||||
* @param {*} user
|
||||
* @param {*} meta
|
||||
* @returns
|
||||
*/
|
||||
async create_session_token (user, meta) {
|
||||
const session = await this.create_session_(user, meta);
|
||||
|
||||
@ -381,10 +369,10 @@ class AuthService extends BaseService {
|
||||
|
||||
|
||||
/**
|
||||
* This method is responsible for authenticating a user or an app from a provided token. It checks the type of the token and performs the necessary actions.
|
||||
* Removes a session with the specified token
|
||||
*
|
||||
* @param {string} token - The token to be authenticated.
|
||||
* @returns {Promise<Actor>} The authenticated user or app actor.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async remove_session_by_token (token) {
|
||||
const decoded = this.modules.jwt.verify(
|
||||
@ -400,12 +388,15 @@ class AuthService extends BaseService {
|
||||
|
||||
|
||||
/**
|
||||
* This method is responsible for authenticating an user or app using an access token.
|
||||
* It decodes the token and checks if it's valid, then it returns an Actor object representing the authenticated user or app.
|
||||
* The method takes a token as input and returns an Actor object as output.
|
||||
* Parameters:
|
||||
* - token: The JWT access token to be authenticated.
|
||||
*/
|
||||
* This method is used to create an access token for a user or an application.
|
||||
*
|
||||
* Access tokens aren't currently used by any of Puter's features.
|
||||
* The feature is kept here for future-use.
|
||||
*
|
||||
* @param {1} authorizer - The actor that is creating the access token.
|
||||
* @param {*} permissions - The permissions to be granted to the access token.
|
||||
* @returns
|
||||
*/
|
||||
async create_access_token (authorizer, permissions) {
|
||||
const jwt_obj = {};
|
||||
const authorizer_obj = {};
|
||||
@ -465,13 +456,14 @@ class AuthService extends BaseService {
|
||||
|
||||
|
||||
/**
|
||||
* This method is used to authenticate a user or an application using an access token.
|
||||
* It decodes the token, checks its type, and verifies it against the database and configuration.
|
||||
* If successful, it returns an Actor object representing the authenticated user or application.
|
||||
*
|
||||
* @param {string} token - The access token to be authenticated.
|
||||
* @return {Actor} - The authenticated user or application object.
|
||||
*/
|
||||
* Get the session list for the specified actor.
|
||||
*
|
||||
* This is primarily used by the `/list-sessions` API endpoint
|
||||
* for the Session Manager in Puter's settings window.
|
||||
*
|
||||
* @param {*} actor - The actor for which to list sessions.
|
||||
* @returns {Promise<Array>} - A list of sessions for the actor.
|
||||
*/
|
||||
async list_sessions (actor) {
|
||||
const seen = new Set();
|
||||
const sessions = [];
|
||||
@ -517,16 +509,12 @@ class AuthService extends BaseService {
|
||||
|
||||
|
||||
/**
|
||||
* This method is responsible for verifying and decoding an access token.
|
||||
* It checks the token type and if it's an 'access-token', it decodes it,
|
||||
* retrieves the user and app from the database, and returns an Actor object
|
||||
* representing the user and app. If the token type is not 'access-token',
|
||||
* it returns an empty object.
|
||||
*
|
||||
* @param {string} token - The access token to be verified and decoded.
|
||||
* @return {Promise<Actor>} - A Promise that resolves to an Actor object
|
||||
* representing the user and app, or an empty object if the token type is not 'access-token'.
|
||||
*/
|
||||
* Revokes a session by UUID. The actor is ignored but should be provided
|
||||
* for future use.
|
||||
*
|
||||
* @param {*} actor
|
||||
* @param {*} uuid
|
||||
*/
|
||||
async revoke_session (actor, uuid) {
|
||||
delete this.sessions[uuid];
|
||||
this.svc_session.remove_session(uuid);
|
||||
@ -534,14 +522,12 @@ class AuthService extends BaseService {
|
||||
|
||||
|
||||
/**
|
||||
* This method is used to authenticate a user or an application using an access token.
|
||||
* It decodes the token and checks if it is valid, then it returns an Actor object representing the authenticated user or application.
|
||||
* If the token is invalid, it throws an error.
|
||||
*
|
||||
* @param {string} token - The access token to be authenticated.
|
||||
* @return {Actor} - An Actor object representing the authenticated user or application.
|
||||
* @throws {LegacyTokenError} - If the token is in an old format.
|
||||
*/
|
||||
* This method is used to create or obtain a user-app token deterministically
|
||||
* from an origin at which puter.js might be embedded.
|
||||
*
|
||||
* @param {*} origin - The origin URL at which puter.js is embedded.
|
||||
* @returns
|
||||
*/
|
||||
async get_user_app_token_from_origin (origin) {
|
||||
origin = this._origin_from_url(origin);
|
||||
const app_uid = await this._app_uid_from_origin(origin);
|
||||
@ -577,12 +563,11 @@ class AuthService extends BaseService {
|
||||
|
||||
|
||||
/**
|
||||
* This method is responsible for authenticating a user or an app using an access token.
|
||||
* It decodes the token and checks if it's valid. If it's valid, it returns an Actor object that represents the authenticated user or app.
|
||||
* The method handles different types of tokens: session, app-under-user, access-token, and actor-site.
|
||||
* @param {string} token - The access token to authenticate.
|
||||
* @returns {Actor} The authenticated user or app represented as an Actor object.
|
||||
*/
|
||||
* Generates a deterministic app uuid from an origin
|
||||
*
|
||||
* @param {*} origin
|
||||
* @returns
|
||||
*/
|
||||
async app_uid_from_origin (origin) {
|
||||
origin = this._origin_from_url(origin);
|
||||
if ( origin === null ) {
|
||||
@ -592,11 +577,6 @@ class AuthService extends BaseService {
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @description This method decodes an access token and checks its validity. It returns the decoded token data if the token is valid, or an error if not.
|
||||
* @param {string} token - The access token to be decoded and checked.
|
||||
* @returns {Object|Error} The decoded token data if the token is valid, or an error if not.
|
||||
*/
|
||||
async _app_uid_from_origin (origin) {
|
||||
// UUIDV5
|
||||
const uuid = this.modules.uuidv5(origin, APP_ORIGIN_UUID_NAMESPACE);
|
||||
|
@ -388,6 +388,7 @@ class PermissionService extends BaseService {
|
||||
* Grants a user permission to interact with another user.
|
||||
*
|
||||
* @param {Actor} actor - The actor granting the permission (must be a user).
|
||||
* @param {string} app_uid - The unique identifier or name of the app.
|
||||
* @param {string} username - The username of the user receiving the permission.
|
||||
* @param {string} permission - The permission string to grant.
|
||||
* @param {Object} [extra={}] - Additional metadata or conditions for the permission.
|
||||
|
@ -27,14 +27,6 @@ const BaseService = require("../BaseService");
|
||||
* allowing for the registration of membership implicators and the retrieval of virtual group data.
|
||||
*/
|
||||
class VirtualGroupService extends BaseService {
|
||||
/**
|
||||
* Retrieves a list of virtual groups based on the provided actor,
|
||||
* utilizing registered membership implicators to determine group membership.
|
||||
*
|
||||
* @param {Object} params - The parameters object.
|
||||
* @param {Object} params.actor - The actor to check against the membership implicators.
|
||||
* @returns {Array} An array of virtual group objects that the actor is a member of.
|
||||
*/
|
||||
_construct () {
|
||||
this.groups_ = {};
|
||||
this.membership_implicators_ = [];
|
||||
@ -56,6 +48,14 @@ class VirtualGroupService extends BaseService {
|
||||
this.groups_[group.id] = group;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves a list of virtual groups based on the provided actor,
|
||||
* utilizing registered membership implicators to determine group membership.
|
||||
*
|
||||
* @param {Object} params - The parameters object.
|
||||
* @param {Object} params.actor - The actor to check against the membership implicators.
|
||||
* @returns {Array} An array of virtual group objects that the actor is a member of.
|
||||
*/
|
||||
get_virtual_groups ({ actor }) {
|
||||
const groups_set = {};
|
||||
|
||||
|
@ -82,21 +82,16 @@ class CoercionService extends BaseService {
|
||||
|
||||
/**
|
||||
* Attempt to coerce a TypedValue to a target TypeSpec.
|
||||
* Note: this is implemented similarly to MultiValue.get.
|
||||
* @param {*} target - the target TypeSpec
|
||||
* @param {*} typed_value - the TypedValue to coerce
|
||||
* @returns {TypedValue|undefined} - the coerced TypedValue, or undefined
|
||||
*/
|
||||
/**
|
||||
* Attempt to coerce a TypedValue to a target TypeSpec.
|
||||
*
|
||||
* This method first adapts the target and the current type of the
|
||||
* TypedValue. If they are equal, it returns the original TypedValue.
|
||||
* Otherwise, it checks if the coercion has been calculated before,
|
||||
* retrieves applicable coercions, and applies them to the TypedValue.
|
||||
*
|
||||
* @param {*} target - the target TypeSpec to which the TypedValue should be coerced
|
||||
* DRY: this is implemented similarly to MultiValue.get.
|
||||
* @param {*} target - the target TypeSpec
|
||||
* @param {*} typed_value - the TypedValue to coerce
|
||||
* @returns {TypedValue|undefined} - the coerced TypedValue if successful, or undefined
|
||||
* @returns {TypedValue|undefined} - the coerced TypedValue, or undefined
|
||||
*/
|
||||
async coerce (target, typed_value) {
|
||||
target = TypeSpec.adapt(target);
|
||||
|
@ -39,13 +39,6 @@ class DriverService extends BaseService {
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @description This method is responsible for registering collections in the registry service.
|
||||
* It registers 'interfaces', 'drivers', and 'types' collections.
|
||||
* It also populates the 'interfaces' and 'types' collections with default interfaces and types.
|
||||
* @returns {void}
|
||||
*/
|
||||
// Add this comment above line 37, before the method definition.
|
||||
_construct () {
|
||||
this.drivers = {};
|
||||
this.interface_to_implementation = {};
|
||||
@ -53,19 +46,18 @@ class DriverService extends BaseService {
|
||||
this.service_aliases = {};
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is responsible for calling a driver's method with provided arguments.
|
||||
* It checks for permissions, selects the best option, and applies rate and monthly usage limits before invoking the driver.
|
||||
*
|
||||
* @param {Object} o - An object containing driver, interface, method, and arguments.
|
||||
* @returns {Promise<{success: boolean, service: DriverService.Driver, result: any, metadata: any}>}
|
||||
*/
|
||||
_init () {
|
||||
const svc_registry = this.services.get('registry');
|
||||
svc_registry.register_collection('');
|
||||
|
||||
const { quot } = strutil;
|
||||
const svc_apiError = this.services.get('api-error');
|
||||
|
||||
/**
|
||||
* There are registered into the new APIErrorService which allows for
|
||||
* better sepration of concerns between APIError and the services which.
|
||||
* depend on it.
|
||||
*/
|
||||
svc_apiError.register({
|
||||
'missing_required_argument': {
|
||||
status: 400,
|
||||
@ -256,7 +248,7 @@ class DriverService extends BaseService {
|
||||
/**
|
||||
* This method retrieves the driver service for the provided interface name.
|
||||
* It first checks if the driver service already exists in the registry,
|
||||
* and if not, it creates a new instance of the driver service and registers it.
|
||||
* and if not, it throws an error.
|
||||
*
|
||||
* @param {string} interfaceName - The name of the interface for which to retrieve the driver service.
|
||||
* @returns {DriverService} The driver service instance for the provided interface.
|
||||
@ -296,12 +288,9 @@ class DriverService extends BaseService {
|
||||
|
||||
|
||||
/**
|
||||
* This method is used to call a specific method on a driver implementation.
|
||||
* It takes in an object containing the driver name, interface name, method name, and arguments, and returns the result of the call.
|
||||
* It also handles error cases, such as missing required arguments, and returns appropriate error messages.
|
||||
* @param {object} o - An object containing the driver name, interface name, method name, and arguments.
|
||||
* @return {Promise<object>} - A promise that resolves to an object containing the result of the call, or an error object if an error occurred.
|
||||
*/
|
||||
* Reserved for future implementation of "best policy" selection.
|
||||
* For now, it just returns the first root option's path.
|
||||
*/
|
||||
async get_policies_for_option_ (option) {
|
||||
// NOT FINAL: before implementing cascading monthly usage,
|
||||
// this return will be removed and the code below it will
|
||||
@ -326,16 +315,25 @@ class DriverService extends BaseService {
|
||||
|
||||
|
||||
/**
|
||||
* Description: This method is responsible for handling driver calls. It takes an object containing the driver name, interface name, method name, and arguments, and calls the corresponding method in the driver implementation.
|
||||
* Behavior: The method first checks if the driver service exists for the given driver name and interface name. If it does, it calls the method in the driver implementation with the provided arguments. If the method is not found, it throws an error. If the driver service does not exist, it throws an error.
|
||||
* Parameters: The method takes an object containing the driver name, interface name, method name, and arguments.
|
||||
* Return Value: The method returns a promise that resolves with an object containing the result of the method call, the metadata of the driver call, and a boolean indicating whether the call was successful.
|
||||
*/
|
||||
// Add this comment above line 276 in DriverService.js
|
||||
* Reserved for future implementation of "best policy" selection.
|
||||
* For now, this just returns the first option of a list of options.
|
||||
*
|
||||
* @param {*} options
|
||||
* @returns
|
||||
*/
|
||||
async select_best_option_ (options) {
|
||||
return options[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is used to call a driver method with provided arguments.
|
||||
* It first processes the arguments to ensure they are of the correct type and format.
|
||||
* Then it checks if the method exists in the interface and if the driver service for that interface is available.
|
||||
* If the method exists and the driver service is available, it calls the method using the driver service.
|
||||
* If the method does not exist or the driver service is not available, it throws an error.
|
||||
* @param {object} o - Object containing driver, interface, method and arguments
|
||||
* @returns {Promise<object>} - Promise that resolves to an object containing the result of the driver method call
|
||||
*/
|
||||
async call_new_ ({
|
||||
actor,
|
||||
service,
|
||||
@ -389,15 +387,6 @@ class DriverService extends BaseService {
|
||||
// when cascading monthly usage is implemented.
|
||||
const svc_systemData = this.services.get('system-data');
|
||||
const svc_su = this.services.get('su');
|
||||
/**
|
||||
* This method is used to call a driver method with provided arguments.
|
||||
* It first processes the arguments to ensure they are of the correct type and format.
|
||||
* Then it checks if the method exists in the interface and if the driver service for that interface is available.
|
||||
* If the method exists and the driver service is available, it calls the method using the driver service.
|
||||
* If the method does not exist or the driver service is not available, it throws an error.
|
||||
* @param {object} o - Object containing driver, interface, method and arguments
|
||||
* @returns {Promise<object>} - Promise that resolves to an object containing the result of the driver method call
|
||||
*/
|
||||
effective_policy = await svc_su.sudo(async () => {
|
||||
return await svc_systemData.interpret(effective_policy.data);
|
||||
});
|
||||
@ -421,13 +410,7 @@ class DriverService extends BaseService {
|
||||
if ( ! effective_policy?.['rate-limit'] ) return args;
|
||||
const svc_su = this.services.get('su');
|
||||
const svc_rateLimit = this.services.get('rate-limit');
|
||||
/**
|
||||
* This method is used to initialize a driver instance with the provided options.
|
||||
* It sets up the necessary dependencies and configurations for the driver to function correctly.
|
||||
*
|
||||
* @param {DriverService} driverService - The instance of the driver service.
|
||||
* @param {Object} options - An object containing the options for the driver instance, such as the driver's implementation, test service, and service aliases.
|
||||
*/
|
||||
|
||||
await svc_su.sudo(policy_holder, async () => {
|
||||
await svc_rateLimit.check_and_increment(
|
||||
`V1:${service_name}:${iface}:${method}`,
|
||||
@ -521,18 +504,8 @@ class DriverService extends BaseService {
|
||||
|
||||
|
||||
/**
|
||||
* This method is responsible for handling driver calls and returns the result or an error message.
|
||||
* It takes a call object with the driver name, interface name, method name, and arguments as input.
|
||||
* The method first checks if the driver and interface exist, then it checks if the user has the required permissions.
|
||||
* If the user has the required permissions, it calls the method on the driver and returns the result.
|
||||
* If the user does not have the required permissions, it throws an APIError with the 'forbidden' message.
|
||||
* If there's an error while calling the method, it throws the error.
|
||||
* If the method returns a TypedValue, it coerces the result to the desired type.
|
||||
* If the method returns an error, it serializes the error and returns it with the original metadata.
|
||||
* @param {Object} call - The call object with driver name, interface name, method name, and arguments.
|
||||
* @returns {Object} The result of the method call or an error object.
|
||||
*/
|
||||
// Add this comment above line 456.
|
||||
* This method converts an error into an appropriate driver response.
|
||||
*/
|
||||
async _driver_response_from_error (e, meta) {
|
||||
let serializable = (e instanceof APIError) || (e instanceof DriverError);
|
||||
return {
|
||||
@ -542,24 +515,15 @@ class DriverService extends BaseService {
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* This method is responsible for registering collections in the service registry.
|
||||
* It registers 'interfaces', 'drivers', and 'types' collections.
|
||||
*/
|
||||
// Above line 465
|
||||
async list_interfaces () {
|
||||
return this.interfaces;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* This method is responsible for registering collections in the service registry.
|
||||
* It registers 'interfaces', 'drivers', and 'types' collections.
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
// line 469
|
||||
* Processes arguments according to the argument types specified
|
||||
* on the interface (in interfaces.js). The behavior of types is
|
||||
* defined in types.js
|
||||
* @param {*} interface_name - the name of the interface
|
||||
* @param {*} method_name - the name of the method
|
||||
* @param {*} args - raw argument values from request body
|
||||
* @returns
|
||||
*/
|
||||
async _process_args (interface_name, method_name, args) {
|
||||
const svc_registry = this.services.get('registry');
|
||||
const c_interfaces = svc_registry.get('interfaces');
|
||||
|
@ -24,20 +24,14 @@ const { stream_to_buffer } = require("../../util/streamutil");
|
||||
const { PassThrough } = require("stream");
|
||||
const { LLRead } = require("../../filesystem/ll_operations/ll_read");
|
||||
|
||||
/**
|
||||
* FileFacade
|
||||
*
|
||||
* This class is used to provide a unified interface for
|
||||
* passing files through the Puter Driver API, and avoiding
|
||||
* unnecessary work such as downloading the file from S3
|
||||
* (when a Puter file is specified) in case the underlying
|
||||
* implementation can accept S3 bucket information instead
|
||||
* of the file's contents.
|
||||
*
|
||||
*
|
||||
*/
|
||||
/**
|
||||
* @class FileFacade
|
||||
* This class is used to provide a unified interface for
|
||||
* passing files through the Puter Driver API, and avoiding
|
||||
* unnecessary work such as downloading the file from S3
|
||||
* (when a Puter file is specified) in case the underlying
|
||||
* implementation can accept S3 bucket information instead
|
||||
* of the file's contents.
|
||||
* @extends AdvancedBase
|
||||
* @description This class provides a unified interface for passing files through the Puter Driver API. It aims to avoid unnecessary operations such as downloading files from S3 when a Puter file is specified, especially if the underlying implementation can accept S3 bucket information instead of the file's contents.
|
||||
*/
|
||||
|
@ -83,7 +83,8 @@ class Construct extends BasicBase {
|
||||
* @class Parameter
|
||||
* @extends Construct
|
||||
* @description The Parameter class extends the Construct class and is used to define a parameter in a method.
|
||||
* It includes properties such as type, optional status, and a description. The class processes raw data to initialize these properties.
|
||||
* It includes properties such as type, whether it's optional, and a description.
|
||||
* The class processes raw data to initialize these properties.
|
||||
*/
|
||||
class Parameter extends Construct {
|
||||
static PROPERTIES = {
|
||||
|
@ -24,7 +24,7 @@ const { TypeSpec } = require("./Construct");
|
||||
/**
|
||||
* Represents an entity in the runtime environment that extends the BasicBase class.
|
||||
* This class serves as a foundational type for creating various runtime constructs
|
||||
* within the Puter framework, enabling the implementation of specialized behaviors
|
||||
* within the drivers subsystem, enabling the implementation of specialized behaviors
|
||||
* and properties.
|
||||
*/
|
||||
class RuntimeEntity extends BasicBase {
|
||||
|
@ -30,16 +30,16 @@ const APIError = require("../../api/APIError");
|
||||
* @description Base class for all type validators in the Puter type system.
|
||||
* Extends AdvancedBase to provide core functionality for type checking and validation.
|
||||
* Serves as the foundation for specialized type classes like String, Flag, NumberType, etc.
|
||||
* Each type has a consolidate method that takes an input value and
|
||||
* returns a sanitized or coerced value appropriate for that input.
|
||||
*/
|
||||
class BaseType extends AdvancedBase {}
|
||||
|
||||
|
||||
/**
|
||||
* @class BaseType
|
||||
* @class String
|
||||
* @extends AdvancedBase
|
||||
* @description Base class for all type validators in the Puter type system.
|
||||
* Extends AdvancedBase to provide core functionality for type checking and validation.
|
||||
* Serves as the foundation for specialized type classes that implement specific validation logic.
|
||||
* @description A class that handles string values in the type system.
|
||||
*/
|
||||
class String extends BaseType {
|
||||
/**
|
||||
@ -71,7 +71,7 @@ class String extends BaseType {
|
||||
* @description A class that handles boolean flag values in the type system.
|
||||
* Converts any input value to a boolean using double negation,
|
||||
* making it useful for command line flags and boolean parameters.
|
||||
* Extends BaseType to integrate with the type validation framework.
|
||||
* Extends BaseType to integrate with the type validation system.
|
||||
*/
|
||||
class Flag extends BaseType {
|
||||
/**
|
||||
|
@ -25,17 +25,11 @@ const { EWMA } = require("../../util/opmath");
|
||||
|
||||
const crypto = require('crypto');
|
||||
|
||||
/**
|
||||
* FileCacheService
|
||||
*
|
||||
* Initial naive cache implementation which stores whole files on disk.
|
||||
* It is assumed that files are only accessed by one server at a given time,
|
||||
* so this will need to be revised when ACL and sharing is implemented.
|
||||
*/
|
||||
/**
|
||||
* @class FileCacheService
|
||||
* @extends AdvancedBase
|
||||
* @description
|
||||
|
||||
* The FileCacheService class manages a cache for file storage and retrieval in the Puter system.
|
||||
* This service provides functionalities to:
|
||||
* - Cache files either in memory (precache) or on disk.
|
||||
@ -148,18 +142,29 @@ class FileCacheService extends AdvancedBase {
|
||||
});
|
||||
}
|
||||
|
||||
_get_path (uid) {
|
||||
const { path_ } = this.modules;
|
||||
return path_.join(this.path, uid);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get the file path for a given file UID.
|
||||
*
|
||||
* @param {string} uid - The unique identifier of the file.
|
||||
* @returns {string} The full path where the file is stored on disk.
|
||||
*/
|
||||
_get_path (uid) {
|
||||
const { path_ } = this.modules;
|
||||
return path_.join(this.path, uid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to retrieve a cached file.
|
||||
*
|
||||
* This method first checks if the file exists in the cache by its UID.
|
||||
* If found, it verifies the file's age against the TTL (time-to-live).
|
||||
* If the file is expired, it invalidates the cache entry. Otherwise,
|
||||
* it returns the cached data or null if not found or invalidated.
|
||||
*
|
||||
* @param {Object} fsNode - The file system node representing the file.
|
||||
* @param {Object} [opt_log] - Optional logging service to log cache hits.
|
||||
* @returns {Promise<Buffer|null>} - The file data if found, or null.
|
||||
*/
|
||||
async try_get(fsNode, opt_log) {
|
||||
const result = await this.try_get_(fsNode, opt_log);
|
||||
this.cache_hit_rate.put(result ? 1 : 0);
|
||||
@ -234,19 +239,13 @@ class FileCacheService extends AdvancedBase {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Attempts to retrieve a cached file.
|
||||
*
|
||||
* This method first checks if the file exists in the cache by its UID.
|
||||
* If found, it verifies the file's age against the TTL (time-to-live).
|
||||
* If the file is expired, it invalidates the cache entry. Otherwise,
|
||||
* it returns the cached data or null if not found or invalidated.
|
||||
*
|
||||
* @param {Object} fsNode - The file system node representing the file.
|
||||
* @param {Object} [opt_log] - Optional logging service to log cache hits.
|
||||
* @returns {Promise<Buffer|null>} - The file data if found, or null.
|
||||
*/
|
||||
* Stores a file in the cache if it's "important enough"
|
||||
* to be in the cache (i.e. wouldn't get immediately evicted).
|
||||
* @param {*} fsNode
|
||||
* @param {*} stream
|
||||
* @returns
|
||||
*/
|
||||
async maybe_store (fsNode, stream) {
|
||||
const size = await fsNode.get('size');
|
||||
|
||||
@ -323,14 +322,9 @@ class FileCacheService extends AdvancedBase {
|
||||
|
||||
|
||||
/**
|
||||
* Invalidates a file from the cache.
|
||||
*
|
||||
* @param {Object} fsNode - The file system node representing the file to invalidate.
|
||||
* @returns {Promise<void>} A promise that resolves when the file has been invalidated from both precache and disk.
|
||||
*
|
||||
* @note This method removes the file's tracker from the cache, deletes the file from precache if present,
|
||||
* and ensures the file is evicted from disk storage if it exists there.
|
||||
*/
|
||||
* Evicts files from precache until there's enough room for a new file.
|
||||
* @param {*} size - The size of the file to be stored.
|
||||
*/
|
||||
async _precache_make_room (size) {
|
||||
if (this._precache_used + size > this.precache_size) {
|
||||
await this._precache_evict(
|
||||
@ -363,15 +357,17 @@ class FileCacheService extends AdvancedBase {
|
||||
|
||||
|
||||
/**
|
||||
* Evicts files from the precache to make room for new files.
|
||||
*
|
||||
* @param {number} capacity_needed - The amount of space needed to be freed in bytes.
|
||||
*
|
||||
* @description
|
||||
* This method sorts all cached files by their score in descending order,
|
||||
* then iterates through them to evict files from the precache to disk
|
||||
* until the required capacity is met. If a file is already on disk, it is skipped.
|
||||
*/
|
||||
* Promotes a file from precache to disk if it has a higher score than the files that would be evicted.
|
||||
*
|
||||
* It may seem unintuitive that going from memory to disk is called a
|
||||
* "promotion". However, the in-memory cache used here is considered a
|
||||
* "precache"; the idea is as soon as we prepare to write a file to disk cache
|
||||
* we're very likely to access it again soon, so we keep it in memory for a
|
||||
* while before writing it to disk.
|
||||
*
|
||||
* @param {*} tracker - The FileTracker instance representing the file to be promoted.
|
||||
* @returns
|
||||
*/
|
||||
async _maybe_promote_to_disk (tracker) {
|
||||
if (tracker.phase !== FileTracker.PHASE_PRECACHE) return;
|
||||
|
||||
|
@ -32,15 +32,6 @@ const MODE_WRITE = Symbol('write');
|
||||
* allowing concurrent read and exclusive write operations.
|
||||
*/
|
||||
class FSLockService extends BaseService {
|
||||
/**
|
||||
* FSLockService handles file system locking mechanisms,
|
||||
* providing methods to acquire read and write locks on paths.
|
||||
* @param {string} path - The path to lock.
|
||||
* @param {string} name - The name of the resource to lock.
|
||||
* @param {symbol} mode - The mode of the lock (read or write).
|
||||
* @returns {Promise} A promise that resolves when the lock is acquired.
|
||||
* @throws {Error} Throws an error if an invalid mode is provided.
|
||||
*/
|
||||
async _construct () {
|
||||
this.locks = {};
|
||||
}
|
||||
@ -87,24 +78,29 @@ class FSLockService extends BaseService {
|
||||
}
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the filesystem lock service by registering the 'fslock' commands.
|
||||
* This method sets up the necessary command handlers and prepares the service
|
||||
* for use. It does not return any value.
|
||||
*/
|
||||
* Lock a file by parent path and child node name.
|
||||
*
|
||||
* @param {string} path - The path to lock.
|
||||
* @param {string} name - The name of the resource to lock.
|
||||
* @param {symbol} mode - The mode of the lock (read or write).
|
||||
* @returns {Promise} A promise that resolves when the lock is acquired.
|
||||
* @throws {Error} Throws an error if an invalid mode is provided.
|
||||
*/
|
||||
async lock_child (path, name, mode) {
|
||||
if ( path.endsWith('/') ) path = path.slice(0, -1);
|
||||
return await this.lock_path(path + '/' + name, mode);
|
||||
}
|
||||
|
||||
/**
|
||||
* Acquires a lock on a child resource, given a path and name.
|
||||
* This method modifies the path to ensure it ends with the correct formatting.
|
||||
*
|
||||
* @param {string} path - The base path of the resource to lock.
|
||||
* @param {string} name - The name of the child resource to lock.
|
||||
* @param {Symbol} mode - The mode of the lock (either MODE_READ or MODE_WRITE).
|
||||
* @returns {Promise} Resolves when the lock has been successfully acquired.
|
||||
*/
|
||||
* Lock a file by path.
|
||||
*
|
||||
* @param {string} path - The path to lock.
|
||||
* @param {symbol} mode - The mode of the lock (read or write).
|
||||
* @returns {Promise} A promise that resolves when the lock is acquired.
|
||||
* @throws {Error} Throws an error if an invalid mode is provided.
|
||||
*/
|
||||
async lock_path (path, mode) {
|
||||
// TODO: Why???
|
||||
// if ( this.locks === undefined ) this.locks = {};
|
||||
|
@ -117,31 +117,6 @@ class InformationObtainer {
|
||||
* // code to obtain fsentry from path
|
||||
* });
|
||||
*/
|
||||
/**
|
||||
* The `InformationService` class is a core component of the information management system.
|
||||
* It facilitates the registration and management of information providers and obtainers,
|
||||
* allowing various services to provide methods for obtaining information and other services
|
||||
* to retrieve that information efficiently. This class optimizes the process by determining
|
||||
* the most efficient strategies for obtaining the required information.
|
||||
*
|
||||
* @class InformationService
|
||||
* @extends BaseService
|
||||
*
|
||||
* @example Obtain an fsentry given a path:
|
||||
*
|
||||
* const infosvc = services.get('information');
|
||||
* const fsentry = await infosvc
|
||||
* .with('fs.fsentry:path').obtain('fs.fsentry')
|
||||
* .exec(path);
|
||||
*
|
||||
* @example Register a method for obtaining an fsentry given a path:
|
||||
*
|
||||
* const infosvc = services.get('information');
|
||||
* infosvc.given('fs.fsentry:path').provide('fs.fsentry')
|
||||
* .addStrategy(async path => {
|
||||
* // code to obtain fsentry from path
|
||||
* });
|
||||
*/
|
||||
class InformationService extends BaseService {
|
||||
/**
|
||||
* @class
|
||||
|
@ -37,12 +37,6 @@ class MonthlyUsageService extends BaseService {
|
||||
/**
|
||||
* Initializes the MonthlyUsageService by setting up the database connection.
|
||||
*
|
||||
* @memberof MonthlyUsageService
|
||||
* @method
|
||||
* @instance
|
||||
* @async
|
||||
* @returns {Promise<void>} A promise that resolves when the initialization is complete.
|
||||
*
|
||||
* @note This method sets the `db` property to a write-enabled database connection for usage data.
|
||||
*/
|
||||
async _init () {
|
||||
|
@ -28,19 +28,6 @@ const { stream_to_the_void, buffer_to_stream } = require('../../util/streamutil'
|
||||
const BaseService = require('../BaseService');
|
||||
|
||||
|
||||
/**
|
||||
* @class HTTPThumbnailService
|
||||
* @extends BaseService
|
||||
* @description
|
||||
* The `HTTPThumbnailService` class manages the creation and retrieval of thumbnails for various file types
|
||||
* over HTTP. It handles queueing thumbnail generation requests, executing them, and interfacing with
|
||||
* a thumbnail generation server. This service supports:
|
||||
* - Queuing and batch processing of thumbnail requests
|
||||
* - Size and MIME type validation for supported files
|
||||
* - Integration with an external thumbnail service via HTTP requests
|
||||
* - Periodic updates of supported MIME types
|
||||
* - Health checks and status reporting for the thumbnail generation process
|
||||
*/
|
||||
class ThumbnailOperation extends TeePromise {
|
||||
// static MAX_RECYCLE_COUNT = 5*3;
|
||||
static MAX_RECYCLE_COUNT = 3;
|
||||
@ -236,17 +223,6 @@ class HTTPThumbnailService extends BaseService {
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Initializes the service by adding a health check for the thumbnail service.
|
||||
*
|
||||
* @private
|
||||
* @method _init
|
||||
* @returns {Promise<void>} A promise that resolves when initialization is complete.
|
||||
* @throws {Error} If there's an error during the initialization process.
|
||||
*
|
||||
* @note This method is called internally during the service setup to ensure
|
||||
* the thumbnail service is operational by pinging it.
|
||||
*/
|
||||
get host_ () {
|
||||
return this.config.host || 'http://127.0.0.1:3101';
|
||||
}
|
||||
@ -260,20 +236,15 @@ class HTTPThumbnailService extends BaseService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Thumbifies a given file by creating a thumbnail.
|
||||
*
|
||||
* @param {object} file - An object describing the file in the same format
|
||||
* as the file object created by multer. The necessary properties are
|
||||
* `buffer`, `filename`, and `mimetype`.
|
||||
* @returns {Promise<string|undefined>} A Promise that resolves to the base64 encoded thumbnail data URL,
|
||||
* or `undefined` if thumbification fails or is not possible.
|
||||
* @throws Will log errors if thumbification process encounters issues.
|
||||
*/
|
||||
/**
|
||||
* Thumbifies a given file by creating a thumbnail.
|
||||
*
|
||||
* @param {Object} file - An object describing the file in the same format as the file object created by multer.
|
||||
* The necessary properties are `buffer`, `filename`, and `mimetype`.
|
||||
* @returns {Promise<string|undefined>} A Promise that resolves to the base64 encoded thumbnail data URL,
|
||||
* or `undefined` if thumbification fails or is not possible.
|
||||
* @throws Will log errors if thumbification process encounters issues.
|
||||
*/
|
||||
async thumbify(file) {
|
||||
const job = new ThumbnailOperation(file);
|
||||
this.queue.push(job);
|
||||
@ -482,12 +453,10 @@ class HTTPThumbnailService extends BaseService {
|
||||
|
||||
|
||||
/**
|
||||
* Sends a request to the thumbnail service to generate thumbnails for the given queue of files.
|
||||
*
|
||||
* @param {Object} options - The options object.
|
||||
* @param {Array} options.queue - An array of ThumbnailOperation jobs to be processed.
|
||||
* @returns {Promise<Object>} - The response from the thumbnail service.
|
||||
* @throws {Error} - If the thumbnail service is not in test mode and fails to respond correctly.
|
||||
* Queries the thumbnail services to check what mime types
|
||||
* are supported for thumbnail generation.
|
||||
* Updates internal state to reflect that.
|
||||
* @returns {Promise<void>} A promise that resolves when the MIME types are updated.
|
||||
*/
|
||||
async query_supported_mime_types_() {
|
||||
const resp = await axios.request(
|
||||
@ -516,12 +485,6 @@ class HTTPThumbnailService extends BaseService {
|
||||
this.constructor.SUPPORTED_MIMETYPES = Object.keys(mime_set);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Queries the supported MIME types from the thumbnail service.
|
||||
* This method is called periodically to update the list of supported MIME types.
|
||||
* @returns {Promise<void>} A promise that resolves when the MIME types are updated.
|
||||
*/
|
||||
async _test ({ assert }) {
|
||||
/**
|
||||
* Runs unit tests for the HTTPThumbnailService.
|
||||
@ -537,43 +500,12 @@ class HTTPThumbnailService extends BaseService {
|
||||
* - Executing thumbnailing jobs in various scenarios to ensure correct behavior.
|
||||
*/
|
||||
this.errors.report = () => {};
|
||||
|
||||
// Pseudo-logger to prevent errors from being thrown when this service
|
||||
// is running under the test kernel.
|
||||
this.log = {
|
||||
/**
|
||||
* Runs a test suite for the HTTPThumbnailService.
|
||||
*
|
||||
* This method sets up a controlled environment for testing,
|
||||
* including stubbing out error reporting and logging methods,
|
||||
* and verifies the behavior of thumbnail operations, queue management,
|
||||
* and error handling in both success and failure scenarios.
|
||||
*
|
||||
* @param {Object} options - Test configuration options.
|
||||
* @param {Function} options.assert - Assertion function for test cases.
|
||||
*/
|
||||
info: () => {},
|
||||
/**
|
||||
* Tests the HTTPThumbnailService class, ensuring:
|
||||
* - Thumbnail operations recycle correctly.
|
||||
* - Thumbnailing requests are processed and the queue is managed properly.
|
||||
* - Errors are handled appropriately in test mode.
|
||||
*
|
||||
* @param {Object} options - An object containing the assert function for testing.
|
||||
* @param {Function} options.assert - Assertion function to validate test conditions.
|
||||
*/
|
||||
error: () => {},
|
||||
/**
|
||||
* Runs the thumbnail service in test mode, allowing for the
|
||||
* verification of thumbnail creation and error handling.
|
||||
*
|
||||
* @param {Object} options - Options for the test.
|
||||
* @param {Function} options.assert - Assertion function to verify test results.
|
||||
*
|
||||
* @description
|
||||
* This method sets up a test environment by:
|
||||
* - Overriding error reporting and logging to suppress output.
|
||||
* - Testing the recycling behavior of ThumbnailOperation.
|
||||
* - Simulating thumbnail requests in test mode to check both successful and failed scenarios.
|
||||
* - Verifying that the queue is properly managed and execution checks are performed.
|
||||
*/
|
||||
noticeme: () => {},
|
||||
};
|
||||
// Thumbnail operation eventually recycles
|
||||
|
@ -48,14 +48,15 @@ class NAPIThumbnailService extends BaseService {
|
||||
is_supported_mimetype (mimetype) {
|
||||
return this.constructor.SUPPORTED_MIMETYPES.includes(mimetype);
|
||||
}
|
||||
is_supported_size (size) {
|
||||
return size <= this.constructor.LIMIT;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a file size is within the supported limit for thumbnail generation
|
||||
* @param {number} size - The file size in bytes to check
|
||||
* @returns {boolean} True if size is less than or equal to the limit, false otherwise
|
||||
*/
|
||||
is_supported_size (size) {
|
||||
return size <= this.constructor.LIMIT;
|
||||
}
|
||||
async thumbify (file) {
|
||||
const transformer = await this.modules.sharp()()
|
||||
.resize(128)
|
||||
|
@ -28,6 +28,8 @@ const { stream_to_buffer } = require('../../util/streamutil');
|
||||
* @description This class represents a thumbnail service that operates entirely in JavaScript without relying on any low-level compiled libraries.
|
||||
* It is designed for development and testing environments due to its CPU-intensive nature, making it less suitable for production deployments.
|
||||
* The service supports various image formats and provides methods to check supported MIME types and file sizes, as well as to generate thumbnails.
|
||||
*
|
||||
* @deprecated as 'sharp' module is now required for app icons anyway
|
||||
*/
|
||||
class PureJSThumbnailService extends BaseService {
|
||||
static DESCRIPTION = `
|
||||
|
@ -41,16 +41,16 @@ class UserProtectedEndpointsService extends BaseService {
|
||||
express: require('express'),
|
||||
};
|
||||
|
||||
/**
|
||||
* Sets up and configures routes for user-protected endpoints.
|
||||
* This method initializes an Express router, applies middleware for authentication,
|
||||
* rate limiting, and session validation, and attaches user-specific endpoints.
|
||||
*
|
||||
* @memberof UserProtectedEndpointsService
|
||||
* @instance
|
||||
* @method __on_install.routes
|
||||
*/
|
||||
['__on_install.routes'] () {
|
||||
/**
|
||||
* Sets up and configures routes for user-protected endpoints.
|
||||
* This method initializes an Express router, applies middleware for authentication,
|
||||
* rate limiting, and session validation, and attaches user-specific endpoints.
|
||||
*
|
||||
* @memberof UserProtectedEndpointsService
|
||||
* @instance
|
||||
* @method __on_install.routes
|
||||
*/
|
||||
const router = (() => {
|
||||
const require = this.require;
|
||||
const express = require('express');
|
||||
@ -96,23 +96,21 @@ class UserProtectedEndpointsService extends BaseService {
|
||||
next();
|
||||
});
|
||||
|
||||
// Require password in request
|
||||
/**
|
||||
* Middleware to validate the provided password against the stored user password.
|
||||
*
|
||||
* This method ensures that the user has entered their current password correctly before
|
||||
* allowing changes to critical account settings. It uses bcrypt for password comparison.
|
||||
*
|
||||
* @param {Object} req - Express request object, containing user and password in body.
|
||||
* @param {Object} res - Express response object for sending back the response.
|
||||
* @param {Function} next - Callback to pass control to the next middleware or route handler.
|
||||
*/
|
||||
router.use(async (req, res, next) => {
|
||||
if ( ! req.body.password ) {
|
||||
return (APIError.create('password_required')).write(res);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Middleware to validate the provided password against the stored user password.
|
||||
*
|
||||
* This method ensures that the user has entered their current password correctly before
|
||||
* allowing changes to critical account settings. It uses bcrypt for password comparison.
|
||||
*
|
||||
* @param {Object} req - Express request object, containing user and password in body.
|
||||
* @param {Object} res - Express response object for sending back the response.
|
||||
* @param {Function} next - Callback to pass control to the next middleware or route handler.
|
||||
*/
|
||||
|
||||
const bcrypt = (() => {
|
||||
const require = this.require;
|
||||
return require('bcrypt');
|
||||
|
Loading…
Reference in New Issue
Block a user