snapshot of https://github.com/RocketChat/Rocket.Chat.git (develop, 2026-09-16; blobs > 131072B omitted)
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Code scanning - action / CodeQL-Build (push) Failing after 2s
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Code scanning - action / CodeQL-Build (push) Failing after 2s
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
This commit is contained in:
@@ -0,0 +1,97 @@
|
||||
/* eslint-disable dot-notation -- we avoid the dot notation here when testing private methods */
|
||||
|
||||
import * as assert from 'node:assert';
|
||||
import * as fs from 'node:fs/promises';
|
||||
import * as path from 'node:path';
|
||||
import { describe, it, afterEach, mock, before, after } from 'node:test';
|
||||
|
||||
import { AppStatus } from '@rocket.chat/apps-engine/definition/AppStatus';
|
||||
import { type RpcStatusType, SuccessObject } from 'jsonrpc-lite';
|
||||
|
||||
import type { AppManager } from '../../../src/server/AppManager';
|
||||
import type { IParseAppPackageResult } from '../../../src/server/compiler';
|
||||
import { AppApiManager } from '../../../src/server/managers';
|
||||
import { DenoRuntimeSubprocessController } from '../../../src/server/runtime/deno/AppsEngineDenoRuntime';
|
||||
import type { IAppStorageItem } from '../../../src/server/storage';
|
||||
import { TestInfastructureSetup } from '../../test-data/utilities';
|
||||
|
||||
describe('DenoRuntimeSubprocessController', () => {
|
||||
const rpcTypeRequest = 'request' as RpcStatusType.request;
|
||||
|
||||
let manager: AppManager;
|
||||
let controller: DenoRuntimeSubprocessController;
|
||||
let appPackage: IParseAppPackageResult;
|
||||
let appStorageItem: IAppStorageItem;
|
||||
|
||||
before(
|
||||
async () => {
|
||||
const infrastructure = new TestInfastructureSetup();
|
||||
manager = infrastructure.getMockManager();
|
||||
|
||||
const api = new AppApiManager(manager);
|
||||
manager.getApiManager = () => api;
|
||||
|
||||
const appPackageBuffer = await fs.readFile(path.join(__dirname, '../../test-data/apps/hello-world-test_0.0.1.zip'));
|
||||
appPackage = await manager.getParser().unpackageApp(appPackageBuffer);
|
||||
|
||||
await fs.unlink(path.join(manager.getTempFilePath(), 'deno-runtime')).catch(function noop() {});
|
||||
|
||||
appStorageItem = {
|
||||
id: 'hello-world-test',
|
||||
status: AppStatus.MANUALLY_ENABLED,
|
||||
} as IAppStorageItem;
|
||||
|
||||
controller = new DenoRuntimeSubprocessController(manager, appPackage, appStorageItem);
|
||||
await controller.setupApp();
|
||||
},
|
||||
{ timeout: 60_000 },
|
||||
);
|
||||
|
||||
afterEach(() => {
|
||||
mock.restoreAll();
|
||||
});
|
||||
|
||||
after(
|
||||
async () => {
|
||||
await controller?.stopApp();
|
||||
await fs.unlink(path.join(manager.getTempFilePath(), 'deno-runtime')).catch((reason) => {
|
||||
console.warn('Failed to delete temporary Deno runtime symlink', reason);
|
||||
});
|
||||
},
|
||||
{ timeout: 30_000 },
|
||||
);
|
||||
|
||||
it('correctly identifies a call to the message bridge', { timeout: 15_000 }, async () => {
|
||||
const messageBridge = manager.getBridges().getMessageBridge();
|
||||
const doCreateSpy = mock.method(messageBridge, 'doCreate', () => Promise.resolve('random-message-id'));
|
||||
|
||||
const messageParam = {
|
||||
room: { id: '123' },
|
||||
sender: { id: '456' },
|
||||
text: 'Hello World',
|
||||
alias: 'alias',
|
||||
avatarUrl: 'https://avatars.com/123',
|
||||
};
|
||||
|
||||
const response = await controller['handleBridgeMessage']({
|
||||
type: rpcTypeRequest,
|
||||
payload: {
|
||||
jsonrpc: '2.0',
|
||||
id: 'requestId',
|
||||
method: 'bridges:getMessageBridge:doCreate',
|
||||
params: [messageParam, 'APP_ID'],
|
||||
serialize: () => '',
|
||||
},
|
||||
});
|
||||
|
||||
assert.ok(response instanceof SuccessObject);
|
||||
|
||||
const { id, result } = response;
|
||||
|
||||
assert.strictEqual(doCreateSpy.mock.calls.length, 1);
|
||||
assert.deepStrictEqual(doCreateSpy.mock.calls[0].arguments, [messageParam, '9c1d62ca-e40f-456f-8601-17c823a16c68']);
|
||||
|
||||
assert.strictEqual(id, 'requestId');
|
||||
assert.strictEqual(result, 'random-message-id');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,237 @@
|
||||
import * as assert from 'node:assert';
|
||||
import * as fs from 'node:fs/promises';
|
||||
import * as os from 'node:os';
|
||||
import * as path from 'node:path';
|
||||
import { describe, it, before, after } from 'node:test';
|
||||
|
||||
import { AppStatus } from '@rocket.chat/apps-engine/definition/AppStatus';
|
||||
import { RoomType } from '@rocket.chat/apps-engine/definition/rooms';
|
||||
|
||||
import { kSecureFields } from '../../../src/lib/SecureFields';
|
||||
import type { AppManager } from '../../../src/server/AppManager';
|
||||
import type { IParseAppPackageResult } from '../../../src/server/compiler';
|
||||
import { AppApiManager } from '../../../src/server/managers';
|
||||
import { DenoRuntimeSubprocessController } from '../../../src/server/runtime/deno/AppsEngineDenoRuntime';
|
||||
import type { IAppStorageItem } from '../../../src/server/storage';
|
||||
import { TestInfastructureSetup } from '../../test-data/utilities';
|
||||
|
||||
/**
|
||||
* These tests verify end-to-end codec compatibility between Node and Deno, specifically
|
||||
* the '@@SecureFields' mechanism introduced to guard access to sensitive room fields
|
||||
* (e.g. abacAttributes) behind app permissions.
|
||||
*
|
||||
* The flow being tested:
|
||||
* 1. Node encodes a room object that includes a '@@SecureFields' descriptor for abacAttributes
|
||||
* using the SECURE_FIELDS_HANDLER_EXT msgpack extension type.
|
||||
* 2. Deno receives and decodes the message. Its codec calls applySecureFields(), which:
|
||||
* - Checks the running app's declared permissions.
|
||||
* - If the app has 'abac.read', it merges abacAttributes into the plain room object.
|
||||
* - Otherwise it strips the field entirely.
|
||||
* 3. The Deno app's checkPreRoomCreatePrevent handler returns Array.isArray(room.abacAttributes),
|
||||
* letting Node observe whether the field was received or withheld.
|
||||
*
|
||||
* Two app fixtures are used:
|
||||
* - secure-fields-test-with-abac_0.0.1.zip → declares { name: 'abac.read' }
|
||||
* - secure-fields-test-no-abac_0.0.1.zip → declares no permissions
|
||||
*/
|
||||
describe('@@SecureFields codec compatibility (Node → Deno)', () => {
|
||||
/** A minimal room that carries abacAttributes as a secure field. */
|
||||
const roomWithSecureField = {
|
||||
id: 'room-secure-fields-test',
|
||||
type: RoomType.CHANNEL,
|
||||
slugifiedName: 'general',
|
||||
displayName: 'General',
|
||||
[kSecureFields]: [
|
||||
{
|
||||
permission: 'abac.read',
|
||||
name: 'abacAttributes',
|
||||
value: [{ key: 'department', values: ['support', 'engineering'] }],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
/** A room with several regular (non-secured) fields plus the secure abacAttributes field. */
|
||||
const roomWithMixedFields = {
|
||||
id: 'room-mixed-fields-test',
|
||||
type: RoomType.CHANNEL,
|
||||
slugifiedName: 'mixed',
|
||||
displayName: 'Mixed',
|
||||
customFields: { foo: 'bar' },
|
||||
messageCount: 42,
|
||||
[kSecureFields]: [
|
||||
{
|
||||
permission: 'abac.read',
|
||||
name: 'abacAttributes',
|
||||
value: [{ key: 'tenant', values: ['alpha'] }],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Shared helpers
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
function buildManager(): AppManager {
|
||||
const infrastructure = new TestInfastructureSetup();
|
||||
const manager = infrastructure.getMockManager();
|
||||
|
||||
const api = new AppApiManager(manager);
|
||||
manager.getApiManager = () => api;
|
||||
|
||||
return manager;
|
||||
}
|
||||
|
||||
async function parseAppPackage(manager: AppManager, zipName: string): Promise<IParseAppPackageResult> {
|
||||
const buf = await fs.readFile(path.join(__dirname, '../../test-data/apps', zipName));
|
||||
return manager.getParser().unpackageApp(buf);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// App WITH abac.read permission
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
describe('app that declares abac.read permission', () => {
|
||||
let manager: AppManager;
|
||||
let controller: DenoRuntimeSubprocessController;
|
||||
let appPackage: IParseAppPackageResult;
|
||||
let appStorageItem: IAppStorageItem;
|
||||
|
||||
before(
|
||||
async () => {
|
||||
manager = buildManager();
|
||||
appPackage = await parseAppPackage(manager, 'secure-fields-test-with-abac_0.0.1.zip');
|
||||
appStorageItem = {
|
||||
id: 'secure-fields-test-with-abac',
|
||||
status: AppStatus.MANUALLY_ENABLED,
|
||||
} as IAppStorageItem;
|
||||
|
||||
controller = new DenoRuntimeSubprocessController(manager, appPackage, appStorageItem);
|
||||
await controller.setupApp();
|
||||
},
|
||||
{ timeout: 60_000 },
|
||||
);
|
||||
|
||||
after(
|
||||
async () => {
|
||||
await controller?.stopApp();
|
||||
await fs.unlink(path.join(os.tmpdir(), 'deno-runtime')).catch(() => undefined);
|
||||
},
|
||||
{ timeout: 30_000 },
|
||||
);
|
||||
|
||||
it('receives abacAttributes when the room is encoded with @@SecureFields', { timeout: 15_000 }, async () => {
|
||||
/**
|
||||
* The app's checkPreRoomCreatePrevent returns Array.isArray(room.abacAttributes).
|
||||
* Because the app has abac.read, Deno's applySecureFields should attach
|
||||
* abacAttributes to the decoded room object, making the result `true`.
|
||||
*/
|
||||
const result = await controller.sendRequest({
|
||||
method: 'app:checkPreRoomCreatePrevent',
|
||||
params: [roomWithSecureField],
|
||||
});
|
||||
|
||||
assert.strictEqual(result, true, 'App with abac.read should receive abacAttributes from a @@SecureFields-encoded room');
|
||||
});
|
||||
|
||||
it('still receives regular (non-secured) room fields alongside the secure field', { timeout: 15_000 }, async () => {
|
||||
/**
|
||||
* Verify that applying secure fields does not discard ordinary room properties.
|
||||
* The handler returns `true` only when abacAttributes is an array AND the
|
||||
* room reached the handler with its other fields intact (the Room constructor
|
||||
* uses Object.assign, so any missing fields would surface as assertion
|
||||
* failures in a more detailed handler – here we at minimum confirm abacAttributes
|
||||
* was applied without corrupting the object).
|
||||
*/
|
||||
const result = await controller.sendRequest({
|
||||
method: 'app:checkPreRoomCreatePrevent',
|
||||
params: [roomWithMixedFields],
|
||||
});
|
||||
|
||||
assert.strictEqual(result, true, 'abacAttributes should be applied to a room that also carries non-secure fields');
|
||||
});
|
||||
|
||||
it('does not throw when the room carries no @@SecureFields descriptor', { timeout: 15_000 }, async () => {
|
||||
/**
|
||||
* Plain rooms (without @@SecureFields) must still be decodable and routable
|
||||
* to the handler. abacAttributes will be absent, so the handler returns false,
|
||||
* but no codec error should be raised.
|
||||
*/
|
||||
const plainRoom = {
|
||||
id: 'plain-room',
|
||||
type: RoomType.CHANNEL,
|
||||
slugifiedName: 'plain',
|
||||
};
|
||||
|
||||
const result = await controller.sendRequest({
|
||||
method: 'app:checkPreRoomCreatePrevent',
|
||||
params: [plainRoom],
|
||||
});
|
||||
|
||||
assert.strictEqual(result, false, 'A plain room (no @@SecureFields) should be decoded normally; abacAttributes absent → false');
|
||||
});
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// App WITHOUT abac.read permission
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
describe('app that does NOT declare abac.read permission', () => {
|
||||
let manager: AppManager;
|
||||
let controller: DenoRuntimeSubprocessController;
|
||||
let appPackage: IParseAppPackageResult;
|
||||
let appStorageItem: IAppStorageItem;
|
||||
|
||||
before(
|
||||
async () => {
|
||||
manager = buildManager();
|
||||
appPackage = await parseAppPackage(manager, 'secure-fields-test-no-abac_0.0.1.zip');
|
||||
appStorageItem = {
|
||||
id: 'secure-fields-test-no-abac',
|
||||
status: AppStatus.MANUALLY_ENABLED,
|
||||
} as IAppStorageItem;
|
||||
|
||||
controller = new DenoRuntimeSubprocessController(manager, appPackage, appStorageItem);
|
||||
await controller.setupApp();
|
||||
},
|
||||
{ timeout: 60_000 },
|
||||
);
|
||||
|
||||
after(
|
||||
async () => {
|
||||
await controller?.stopApp();
|
||||
await fs.unlink(path.join(os.tmpdir(), 'deno-runtime')).catch(() => undefined);
|
||||
},
|
||||
{ timeout: 30_000 },
|
||||
);
|
||||
|
||||
it('does not receive abacAttributes when the app lacks abac.read permission', { timeout: 15_000 }, async () => {
|
||||
/**
|
||||
* The room is encoded with @@SecureFields for abacAttributes, but this app
|
||||
* does not declare abac.read. Deno's applySecureFields should withhold the
|
||||
* field, so the handler returns `false`.
|
||||
*/
|
||||
const result = await controller.sendRequest({
|
||||
method: 'app:checkPreRoomCreatePrevent',
|
||||
params: [roomWithSecureField],
|
||||
});
|
||||
|
||||
assert.strictEqual(result, false, 'App without abac.read must not receive abacAttributes from a @@SecureFields-encoded room');
|
||||
});
|
||||
|
||||
it('still decodes regular (non-secured) room fields correctly', { timeout: 15_000 }, async () => {
|
||||
/**
|
||||
* Even though abacAttributes is withheld, the remaining room properties
|
||||
* (id, type, slugifiedName, customFields, messageCount, …) must survive
|
||||
* the round-trip unaltered. The handler only inspects abacAttributes, so
|
||||
* we verify this indirectly: if the room object were corrupted entirely,
|
||||
* Deno would throw an error instead of returning a clean `false`.
|
||||
*/
|
||||
const result = await controller.sendRequest({
|
||||
method: 'app:checkPreRoomCreatePrevent',
|
||||
params: [roomWithMixedFields],
|
||||
});
|
||||
|
||||
assert.strictEqual(result, false, 'Regular room fields should survive the codec round-trip even when a secure field is withheld');
|
||||
});
|
||||
});
|
||||
});
|
||||
271
packages/apps/tests/server/runtime/deno/LivenessManager.test.ts
Normal file
271
packages/apps/tests/server/runtime/deno/LivenessManager.test.ts
Normal file
@@ -0,0 +1,271 @@
|
||||
import * as assert from 'node:assert';
|
||||
import type { ChildProcess } from 'node:child_process';
|
||||
import { EventEmitter } from 'node:stream';
|
||||
import { describe, it, beforeEach, afterEach, mock, type Mock } from 'node:test';
|
||||
|
||||
import debugFactory from 'debug';
|
||||
|
||||
import type { BaseRuntimeSubprocessController } from '../../../../src/server/runtime/base/BaseRuntimeSubprocessController';
|
||||
import { COMMAND_PING, LivenessManager } from '../../../../src/server/runtime/base/LivenessManager';
|
||||
import { ProcessMessenger } from '../../../../src/server/runtime/base/ProcessMessenger';
|
||||
|
||||
describe('LivenessManager ping mechanism', () => {
|
||||
const PING_INTERVAL_MS = 100;
|
||||
const PING_TIMEOUT_MS = 50;
|
||||
const CONSECUTIVE_TIMEOUT_LIMIT = 3;
|
||||
const MAX_RESTARTS = Infinity;
|
||||
const RESTART_ATTEMPT_DELAY_MS = 10;
|
||||
|
||||
let mockController: BaseRuntimeSubprocessController;
|
||||
let mockMessenger: ProcessMessenger;
|
||||
let mockSubprocess: ChildProcess;
|
||||
let debug: debug.Debugger;
|
||||
let livenessManager: LivenessManager;
|
||||
let controllerEventEmitter: EventEmitter;
|
||||
let subprocessEventEmitter: EventEmitter;
|
||||
let sendMock: Mock<ProcessMessenger['send']>;
|
||||
|
||||
beforeEach(() => {
|
||||
debug = debugFactory('test:liveness-manager');
|
||||
mock.timers.enable({ apis: ['setTimeout', 'setInterval', 'Date'] });
|
||||
mock.timers.setTime(0);
|
||||
|
||||
// Create event emitters for controller and subprocess
|
||||
controllerEventEmitter = new EventEmitter();
|
||||
subprocessEventEmitter = new EventEmitter();
|
||||
|
||||
// Mock controller
|
||||
mockController = {
|
||||
getProcessState: () => 'ready',
|
||||
restartApp: async () => Promise.resolve(),
|
||||
stopApp: async () => Promise.resolve(),
|
||||
on: (event: string, listener: (...args: any[]) => void) => {
|
||||
controllerEventEmitter.on(event, listener);
|
||||
return mockController;
|
||||
},
|
||||
once: (event: string, listener: (...args: any[]) => void) => {
|
||||
controllerEventEmitter.once(event, listener);
|
||||
return mockController;
|
||||
},
|
||||
off: (event: string, listener: (...args: any[]) => void) => {
|
||||
controllerEventEmitter.off(event, listener);
|
||||
return mockController;
|
||||
},
|
||||
emit: (event: string, ...args: any[]) => {
|
||||
return controllerEventEmitter.emit(event, ...args);
|
||||
},
|
||||
addListener: () => mockController,
|
||||
removeListener: () => mockController,
|
||||
removeAllListeners: () => mockController,
|
||||
setMaxListeners: () => mockController,
|
||||
getMaxListeners: () => 10,
|
||||
listeners: (): any[] => [],
|
||||
rawListeners: (): any[] => [],
|
||||
listenerCount: (): number => 0,
|
||||
prependListener: () => mockController,
|
||||
prependOnceListener: () => mockController,
|
||||
eventNames: (): string[] => [],
|
||||
} as unknown as BaseRuntimeSubprocessController;
|
||||
|
||||
// Mock subprocess
|
||||
mockSubprocess = {
|
||||
pid: 12345,
|
||||
once: (event: string, listener: (...args: any[]) => void) => {
|
||||
subprocessEventEmitter.once(event, listener);
|
||||
return mockSubprocess;
|
||||
},
|
||||
on: () => mockSubprocess,
|
||||
off: () => mockSubprocess,
|
||||
emit: (event: string, ...args: any[]) => {
|
||||
return subprocessEventEmitter.emit(event, ...args);
|
||||
},
|
||||
} as unknown as ChildProcess;
|
||||
|
||||
// Mock messenger
|
||||
mockMessenger = new ProcessMessenger();
|
||||
mockMessenger.setReceiver(mockSubprocess);
|
||||
|
||||
sendMock = mock.method(mockMessenger, 'send', () => Promise.resolve());
|
||||
|
||||
// Create LivenessManager with fast ping options for testing
|
||||
livenessManager = new LivenessManager(
|
||||
{
|
||||
controller: mockController,
|
||||
messenger: mockMessenger,
|
||||
debug,
|
||||
},
|
||||
{
|
||||
pingTimeoutInMS: PING_TIMEOUT_MS,
|
||||
pingIntervalInMS: PING_INTERVAL_MS,
|
||||
consecutiveTimeoutLimit: CONSECUTIVE_TIMEOUT_LIMIT,
|
||||
maxRestarts: MAX_RESTARTS,
|
||||
restartAttemptDelayInMS: RESTART_ATTEMPT_DELAY_MS,
|
||||
},
|
||||
);
|
||||
|
||||
livenessManager.attach(mockSubprocess);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// Stop the liveness manager to clean up intervals
|
||||
livenessManager.stop();
|
||||
|
||||
// Clear all event listeners
|
||||
controllerEventEmitter.removeAllListeners();
|
||||
subprocessEventEmitter.removeAllListeners();
|
||||
|
||||
mock.timers.reset();
|
||||
sendMock.mock.restore();
|
||||
});
|
||||
|
||||
it('should update lastHeartbeatTimestamp when heartbeat event is emitted', () => {
|
||||
controllerEventEmitter.emit('constructed');
|
||||
|
||||
const initialTimestamp = livenessManager.getRuntimeData().lastHeartbeatTimestamp;
|
||||
assert.strictEqual(initialTimestamp, 0);
|
||||
|
||||
mock.timers.tick(50);
|
||||
|
||||
controllerEventEmitter.emit('heartbeat');
|
||||
|
||||
const newTimestamp = livenessManager.getRuntimeData().lastHeartbeatTimestamp;
|
||||
assert.strictEqual(newTimestamp, 50);
|
||||
});
|
||||
|
||||
it('should ping when heartbeat is stale', () => {
|
||||
controllerEventEmitter.emit('constructed');
|
||||
|
||||
mock.timers.tick(PING_INTERVAL_MS);
|
||||
|
||||
assert.strictEqual(sendMock.mock.calls.length, 1);
|
||||
assert.deepStrictEqual(sendMock.mock.calls[0].arguments, [COMMAND_PING]);
|
||||
});
|
||||
|
||||
it('should not ping when heartbeat is recent', () => {
|
||||
controllerEventEmitter.emit('constructed');
|
||||
|
||||
// Wait half the interval to update the heartbeat
|
||||
mock.timers.tick(PING_INTERVAL_MS / 2);
|
||||
|
||||
controllerEventEmitter.emit('heartbeat');
|
||||
|
||||
// Wait for the rest of the interval that would trigger the ping
|
||||
mock.timers.tick(PING_INTERVAL_MS / 2);
|
||||
|
||||
// Ping should not have been sent
|
||||
assert.strictEqual(sendMock.mock.calls.length, 0);
|
||||
});
|
||||
|
||||
it('should handle successful ping/pong', () => {
|
||||
controllerEventEmitter.emit('constructed');
|
||||
|
||||
// Wait for the full interval
|
||||
mock.timers.tick(PING_INTERVAL_MS);
|
||||
|
||||
// Verify ping was sent
|
||||
assert.strictEqual(sendMock.mock.calls.length, 1);
|
||||
assert.deepStrictEqual(sendMock.mock.calls[0].arguments, [COMMAND_PING]);
|
||||
|
||||
// Advance time to simulate latency
|
||||
mock.timers.tick(20);
|
||||
|
||||
// Emit pong response
|
||||
controllerEventEmitter.emit('pong');
|
||||
|
||||
// Verify consecutive timeout count was reset
|
||||
const runtimeData = livenessManager.getRuntimeData();
|
||||
assert.strictEqual(runtimeData.pingTimeoutConsecutiveCount, 0);
|
||||
|
||||
// Verify heartbeat timestamp was updated
|
||||
const newTimestamp = runtimeData.lastHeartbeatTimestamp;
|
||||
assert.strictEqual(newTimestamp, PING_INTERVAL_MS + 20);
|
||||
});
|
||||
|
||||
it('should keep track of consecutive timeouts, and clear the count on a heartbeat', () => {
|
||||
controllerEventEmitter.emit('constructed');
|
||||
|
||||
// Wait for the full interval
|
||||
mock.timers.tick(PING_INTERVAL_MS);
|
||||
|
||||
// Verify ping was sent
|
||||
assert.strictEqual(sendMock.mock.calls.length, 1);
|
||||
assert.deepStrictEqual(sendMock.mock.calls[0].arguments, [COMMAND_PING]);
|
||||
|
||||
// Timeout the ping
|
||||
mock.timers.tick(PING_TIMEOUT_MS);
|
||||
|
||||
// Verify consecutive timeout count incremented
|
||||
let runtimeData = livenessManager.getRuntimeData();
|
||||
assert.strictEqual(runtimeData.pingTimeoutConsecutiveCount, 1);
|
||||
|
||||
// Tick the rest of the interval to next ping
|
||||
mock.timers.tick(PING_INTERVAL_MS - PING_TIMEOUT_MS);
|
||||
|
||||
// Verify ping was sent
|
||||
assert.strictEqual(sendMock.mock.calls.length, 2);
|
||||
|
||||
// Timeout the ping
|
||||
mock.timers.tick(PING_TIMEOUT_MS);
|
||||
|
||||
// Verify consecutive timeout count incremented
|
||||
runtimeData = livenessManager.getRuntimeData();
|
||||
assert.strictEqual(runtimeData.pingTimeoutConsecutiveCount, 2);
|
||||
|
||||
controllerEventEmitter.emit('heartbeat');
|
||||
|
||||
mock.timers.tick(PING_INTERVAL_MS - PING_TIMEOUT_MS);
|
||||
|
||||
// Shouldn't have called ping due to recent heartbeat
|
||||
assert.strictEqual(sendMock.mock.calls.length, 2);
|
||||
|
||||
// Verify consecutive timeout count was reset
|
||||
runtimeData = livenessManager.getRuntimeData();
|
||||
assert.strictEqual(runtimeData.pingTimeoutConsecutiveCount, 0);
|
||||
});
|
||||
|
||||
it('should call restart when consecutive timeout count reaches limit from options', async () => {
|
||||
(livenessManager as any).options.consecutiveTimeoutLimit = 2;
|
||||
const restartSpy = mock.method(livenessManager as any, 'restartProcess', () => Promise.resolve());
|
||||
|
||||
controllerEventEmitter.emit('constructed');
|
||||
|
||||
// Wait for the full interval
|
||||
mock.timers.tick(PING_INTERVAL_MS);
|
||||
|
||||
// Verify ping was sent
|
||||
assert.strictEqual(sendMock.mock.calls.length, 1);
|
||||
assert.deepStrictEqual(sendMock.mock.calls[0].arguments, [COMMAND_PING]);
|
||||
|
||||
// Timeout the ping
|
||||
mock.timers.tick(PING_TIMEOUT_MS);
|
||||
|
||||
// Verify consecutive timeout count incremented
|
||||
let runtimeData = livenessManager.getRuntimeData();
|
||||
assert.strictEqual(runtimeData.pingTimeoutConsecutiveCount, 1);
|
||||
|
||||
// Wait for ping handler to finish
|
||||
await livenessManager.getPendingPing();
|
||||
|
||||
// Tick the rest of the interval to next ping
|
||||
mock.timers.tick(PING_INTERVAL_MS - PING_TIMEOUT_MS);
|
||||
|
||||
// Verify ping was sent
|
||||
assert.strictEqual(sendMock.mock.calls.length, 2);
|
||||
|
||||
// Timeout the ping
|
||||
mock.timers.tick(PING_TIMEOUT_MS);
|
||||
|
||||
// Wait for ping handler to finish
|
||||
await livenessManager.getPendingPing();
|
||||
|
||||
// Verify consecutive timeout count incremented
|
||||
runtimeData = livenessManager.getRuntimeData();
|
||||
assert.strictEqual(runtimeData.pingTimeoutConsecutiveCount, 2);
|
||||
|
||||
// Verify that restart has been called due to reaching consecutive timeout limit
|
||||
assert.strictEqual(restartSpy.mock.calls.length, 1);
|
||||
assert.deepStrictEqual(restartSpy.mock.calls[0].arguments, ['Too many pings timed out']);
|
||||
|
||||
restartSpy.mock.restore();
|
||||
});
|
||||
});
|
||||
107
packages/apps/tests/server/runtime/deno/bundleLegacyApp.test.ts
Normal file
107
packages/apps/tests/server/runtime/deno/bundleLegacyApp.test.ts
Normal file
@@ -0,0 +1,107 @@
|
||||
import * as assert from 'node:assert';
|
||||
import { describe, it } from 'node:test';
|
||||
|
||||
import type { AppImplements } from '../../../../src/server/compiler/AppImplements';
|
||||
import type { IParseAppPackageResult } from '../../../../src/server/compiler/IParseAppPackageResult';
|
||||
import { bundleLegacyApp } from '../../../../src/server/runtime/base/bundler';
|
||||
|
||||
function makeAppPackage(classFile: string, files: { [key: string]: string }): IParseAppPackageResult {
|
||||
return {
|
||||
info: {
|
||||
id: 'test-app',
|
||||
name: 'Test App',
|
||||
nameSlug: 'test-app',
|
||||
version: '0.0.1',
|
||||
description: 'Test App',
|
||||
requiredApiVersion: '*',
|
||||
classFile,
|
||||
iconFile: 'icon.png',
|
||||
implements: [],
|
||||
author: { name: 'Test', homepage: 'https://test.com', support: 'https://test.com' },
|
||||
},
|
||||
files,
|
||||
languageContent: {},
|
||||
implemented: {} as AppImplements,
|
||||
};
|
||||
}
|
||||
|
||||
describe('bundleLegacyApp', () => {
|
||||
it('bundles a single-file app into one output file', async () => {
|
||||
const appPackage = makeAppPackage('app.js', {
|
||||
'app.js': 'module.exports = { hello: "world" };',
|
||||
});
|
||||
|
||||
await bundleLegacyApp(appPackage);
|
||||
|
||||
// After bundling, files should contain only the single bundled entry
|
||||
assert.strictEqual(Object.keys(appPackage.files).length, 1);
|
||||
assert.ok(appPackage.files['app.js'] !== undefined);
|
||||
assert.strictEqual(typeof appPackage.files['app.js'], 'string');
|
||||
assert.ok(appPackage.files['app.js'].length > 0);
|
||||
});
|
||||
|
||||
it('includes code from relative imports', async () => {
|
||||
const appPackage = makeAppPackage('app.js', {
|
||||
'app.js': 'var utils = require("./utils"); module.exports = utils;',
|
||||
'utils.js': 'module.exports = { value: 42 };',
|
||||
});
|
||||
|
||||
await bundleLegacyApp(appPackage);
|
||||
|
||||
assert.strictEqual(Object.keys(appPackage.files).length, 1);
|
||||
// The bundled output should contain the inlined value from utils.js
|
||||
assert.ok(appPackage.files['app.js'].includes('42'));
|
||||
});
|
||||
|
||||
it('resolves directory index imports (require("./dir") → dir/index.js)', async () => {
|
||||
const appPackage = makeAppPackage('app.js', {
|
||||
'app.js': 'var lib = require("./lib"); module.exports = lib;',
|
||||
'lib/index.js': 'module.exports = { fromIndex: true };',
|
||||
});
|
||||
|
||||
await bundleLegacyApp(appPackage);
|
||||
|
||||
assert.strictEqual(Object.keys(appPackage.files).length, 1);
|
||||
assert.ok(appPackage.files['app.js'].includes('fromIndex'));
|
||||
});
|
||||
|
||||
it('marks @rocket.chat/apps-engine/* imports as external', async () => {
|
||||
const appPackage = makeAppPackage('app.js', {
|
||||
'app.js': ['var AppInterface = require("@rocket.chat/apps-engine/definition/AppInterface");', 'module.exports = AppInterface;'].join(
|
||||
'\n',
|
||||
),
|
||||
});
|
||||
|
||||
await bundleLegacyApp(appPackage);
|
||||
|
||||
assert.strictEqual(Object.keys(appPackage.files).length, 1);
|
||||
// The apps-engine import should remain as an external require, not be inlined
|
||||
assert.ok(appPackage.files['app.js'].includes('@rocket.chat/apps-engine'));
|
||||
});
|
||||
|
||||
it('handles deeply nested relative imports', async () => {
|
||||
const appPackage = makeAppPackage('app.js', {
|
||||
'app.js': 'var a = require("./commands/run"); module.exports = a;',
|
||||
'commands/run.js': 'var helper = require("../helpers/format"); module.exports = helper;',
|
||||
'helpers/format.js': 'module.exports = { formatted: true };',
|
||||
});
|
||||
|
||||
await bundleLegacyApp(appPackage);
|
||||
|
||||
assert.strictEqual(Object.keys(appPackage.files).length, 1);
|
||||
assert.ok(appPackage.files['app.js'].includes('formatted'));
|
||||
});
|
||||
|
||||
it('replaces the files record with only the bundled classFile entry', async () => {
|
||||
const appPackage = makeAppPackage('main.js', {
|
||||
'main.js': 'var dep = require("./dep"); module.exports = dep;',
|
||||
'dep.js': 'module.exports = "dep-value";',
|
||||
'unused.js': 'module.exports = "unused";',
|
||||
});
|
||||
|
||||
await bundleLegacyApp(appPackage);
|
||||
|
||||
// Only the classFile key should remain after bundling
|
||||
assert.deepStrictEqual(Object.keys(appPackage.files), ['main.js']);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user