Skip to content

Commit

Permalink
chore(cosmic-swingset): Type-check JS files (#10539)
Browse files Browse the repository at this point in the history
## Description
At long last!

### Security Considerations
n/a

### Scaling Considerations
n/a

### Documentation Considerations
n/a

### Testing Considerations
n/a

### Upgrade Considerations
n/a
  • Loading branch information
mergify[bot] authored Nov 21, 2024
2 parents 9d6cff1 + a9fdcea commit a7bee20
Show file tree
Hide file tree
Showing 13 changed files with 65 additions and 41 deletions.
4 changes: 2 additions & 2 deletions packages/cosmic-swingset/src/anylogger-agoric.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ const selectedCode = anylogger.levels[selectedLevel];
const globalCode = selectedCode === undefined ? -Infinity : selectedCode;

const oldExt = anylogger.ext;
anylogger.ext = (l, o) => {
l = oldExt(l, o);
anylogger.ext = logger => {
const l = oldExt(logger);
l.enabledFor = lvl => globalCode >= anylogger.levels[lvl];

const prefix = l.name.replace(/:/g, ': ');
Expand Down
8 changes: 6 additions & 2 deletions packages/cosmic-swingset/src/chain-main.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// @ts-check

import path from 'node:path';
import nativePath from 'node:path';
import v8 from 'node:v8';
import process from 'node:process';
import fs from 'node:fs';
Expand Down Expand Up @@ -167,7 +167,11 @@ const makePrefixedBridgeStorage = (
});
};

export default async function main(progname, args, { env, homedir, agcc }) {
export default async function main(
progname,
args,
{ env, homedir, path = nativePath, agcc },
) {
const portNums = {};

// TODO: use the 'basedir' pattern
Expand Down
4 changes: 2 additions & 2 deletions packages/cosmic-swingset/src/entrypoint.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ import main from './chain-main.js';
const log = anylogger('ag-chain-cosmos');

main(process.argv[1], process.argv.splice(2), {
path,
homedir: os.homedir(),
env: process.env,
homedir: os.homedir(),
path,
agcc,
}).then(
_res => 0,
Expand Down
20 changes: 9 additions & 11 deletions packages/cosmic-swingset/src/helpers/bufferedStorage.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { assert, Fail } from '@endo/errors';
// XXX Do these "StorageAPI" functions belong in their own package?

/**
* @template {unknown} [T=unknown]
* @template [T=unknown]
* @typedef {{
* has: (key: string) => boolean,
* get: (key: string) => T | undefined,
Expand All @@ -16,7 +16,7 @@ import { assert, Fail } from '@endo/errors';
*/

/**
* @template {unknown} [T=unknown]
* @template [T=unknown]
* @typedef {KVStore<T> & {commit: () => void, abort: () => void}} BufferedKVStore
*/

Expand Down Expand Up @@ -210,15 +210,13 @@ export function provideEnhancedKVStore(mapOrKvStore = new Map()) {
* until told to commit (or abort) them.
*
* @template [T=unknown]
* @param {KVStore<T>} kvStore The StorageAPI object to wrap
* @param {{
* onGet?: (key: string, value: T | undefined) => void, // a callback invoked after getting a value from kvStore
* onPendingSet?: (key: string, value: T) => void, // a callback invoked after a new uncommitted value is set
* onPendingDelete?: (key: string) => void, // a callback invoked after a new uncommitted delete
* onCommit?: () => void, // a callback invoked after pending operations have been committed
* onAbort?: () => void, // a callback invoked after pending operations have been aborted
* }} listeners Optional callbacks to be invoked when respective events occur
*
* @param {KVStore<T>} kvStore the StorageAPI object to wrap
* @param {object} [listeners] optional callbacks to be invoked when respective events occur
* @param {(key: string, value: T | undefined) => void} [listeners.onGet] a callback invoked after getting a value from kvStore
* @param {(key: string, value: T) => void} [listeners.onPendingSet] a callback invoked after a new uncommitted value is set
* @param {(key: string) => void} [listeners.onPendingDelete] a callback invoked after a new uncommitted delete
* @param {() => void} [listeners.onCommit] a callback invoked after pending operations have been committed
* @param {() => void} [listeners.onAbort] a callback invoked after pending operations have been aborted
* @returns {{kvStore: KVStore<T>} & Pick<BufferedKVStore<T>, 'commit' | 'abort'>}
*/
export function makeBufferedStorage(kvStore, listeners = {}) {
Expand Down
54 changes: 35 additions & 19 deletions packages/cosmic-swingset/src/sim-chain.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,40 +19,48 @@ import { launch } from './launch-chain.js';
import { getTelemetryProviders } from './kernel-stats.js';
import { DEFAULT_SIM_SWINGSET_PARAMS, QueueInbound } from './sim-params.js';
import { parseQueueSizes } from './params.js';
import { makeKVStoreFromMap } from './helpers/bufferedStorage.js';
import { makeQueue, makeQueueStorageMock } from './helpers/make-queue.js';

/** @import { Mailbox } from '@agoric/swingset-vat' */

const console = anylogger('fake-chain');

const TELEMETRY_SERVICE_NAME = 'sim-cosmos';

const PRETEND_BLOCK_DELAY = 5;
const scaleBlockTime = ms => Math.floor(ms / 1000);

async function makeMapStorage(file) {
let content;
async function makeMailboxStorageFromFile(file) {
/** @type {Map<string, Mailbox>} */
const map = new Map();
map.commit = async () => {
const kvStore = makeKVStoreFromMap(map);
const commit = async () => {
const obj = {};
for (const [k, v] of map.entries()) {
obj[k] = exportMailbox(v);
}
const json = stringify(obj);
await fs.promises.writeFile(file, json);
};

await (async () => {
content = await fs.promises.readFile(file);
const read = async () => {
const content = await fs.promises.readFile(file, 'utf8');
return JSON.parse(content);
})().then(
obj => {
for (const [k, v] of Object.entries(obj)) {
map.set(k, importMailbox(v));
}
},
() => {},
);
};
const load = async obj => {
map.clear();
for (const [k, v] of Object.entries(obj)) {
map.set(k, importMailbox(v));
}
};
const reset = async () => {
const obj = await read();
await load(obj);
};

return map;
await read().then(load, () => {});

return { ...kvStore, commit, abort: reset };
}

export async function connectToFakeChain(basedir, GCI, delay, inbound) {
Expand All @@ -61,7 +69,7 @@ export async function connectToFakeChain(basedir, GCI, delay, inbound) {
const mailboxFile = path.join(basedir, `fake-chain-${GCI}-mailbox.json`);
const bootAddress = `${GCI}-client`;

const mailboxStorage = await makeMapStorage(mailboxFile);
const mailboxStorage = await makeMailboxStorageFromFile(mailboxFile);

const argv = {
giveMeAllTheAgoricPowers: true,
Expand Down Expand Up @@ -109,6 +117,7 @@ export async function connectToFakeChain(basedir, GCI, delay, inbound) {
const actionQueue = makeQueue(actionQueueStorage);

const s = await launch({
bridgeOutbound: /** @type {any} */ (undefined),
actionQueueStorage,
highPriorityQueueStorage,
kernelStateDBDir: stateDBdir,
Expand All @@ -120,13 +129,20 @@ export async function connectToFakeChain(basedir, GCI, delay, inbound) {
debugName: GCI,
metricsProvider,
slogSender,
swingsetConfig: {},
});

const { blockingSend, savedHeight } = s;

let blockHeight = savedHeight;
const intoChain = [];
let nextBlockTimeout = 0;
/** @type {undefined | ReturnType<typeof setTimeout>} */
let nextBlockTimeout;
const resetNextBlockTimeout = () => {
if (nextBlockTimeout === undefined) return;
clearTimeout(nextBlockTimeout);
nextBlockTimeout = undefined;
};

const maximumDelay = (delay || PRETEND_BLOCK_DELAY) * 1000;

Expand Down Expand Up @@ -172,7 +188,7 @@ export async function connectToFakeChain(basedir, GCI, delay, inbound) {
// Done processing, "commit the block".
await blockingSend({ type: 'COMMIT_BLOCK', blockHeight, blockTime });

clearTimeout(nextBlockTimeout);
resetNextBlockTimeout();
nextBlockTimeout = setTimeout(simulateBlock, maximumDelay);

// TODO: maybe add latency to the inbound messages.
Expand All @@ -197,7 +213,7 @@ export async function connectToFakeChain(basedir, GCI, delay, inbound) {
// Only actually simulate a block if we're not in bootstrap.
let p;
if (blockHeight && !delay) {
clearTimeout(nextBlockTimeout);
resetNextBlockTimeout();
p = simulateBlock();
}
await p;
Expand Down
2 changes: 2 additions & 0 deletions packages/cosmic-swingset/test/clean-core-eval.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import {
} from '../scripts/clean-core-eval.js';

test('defangEvaluableCode is working', t => {
/** @typedef {import('ava').ThrowsExpectation<Error>} EvaluationExpectation */
/** @type {Array<[string, string?, EvaluationExpectation?, EvaluationExpectation?]>} */
const samples = [
[''],
[
Expand Down
1 change: 1 addition & 0 deletions packages/cosmic-swingset/test/gov-code.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/* global E */
/// <reference types="@agoric/vats/src/core/core-eval-env" />
/**
* This file, along with the companion `gov-permit.json`, are used to test "big
* hammer" chain governance. They don't have a functional purpose outside of
Expand Down
3 changes: 2 additions & 1 deletion packages/cosmic-swingset/test/provision-smartwallet.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ test.before(async t => {
const io = { spawn: ambientSpawn, cwd: makefileDir };
const pspawnMake = pspawn('make', io);
const pspawnAgd = pspawn('bin/ag-chain-cosmos', io);
const scenario2 = makeScenario2({ pspawnMake, pspawnAgd, delay, log: t.log });
const scenario2 = makeScenario2({ pspawnMake, pspawnAgd, log: t.log });
const walletTool = makeWalletTool({
runMake: scenario2.runMake,
pspawnAgd,
Expand All @@ -65,6 +65,7 @@ test.before(async t => {
// if run with the test above.
// TODO: https://github.com/Agoric/agoric-sdk/issues/6766
test.skip('integration test: smart wallet provision', async t => {
// @ts-expect-error context has unknown type
const { scenario2, walletTool, soloAddr } = t.context;

const enoughBlocksToProvision = 7;
Expand Down
2 changes: 2 additions & 0 deletions packages/cosmic-swingset/test/run-policy.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
makeVatCleanupBudgetFromKeywords,
} from '../src/sim-params.js';

/** @import { ManagerType, SwingSetConfig } from '@agoric/swingset-vat' */
/** @import { KVStore } from '../src/helpers/bufferedStorage.js' */

/**
Expand Down Expand Up @@ -59,6 +60,7 @@ test('cleanup work must be limited by vat_cleanup_budget', async t => {
bundles: makeSourceDescriptors({
puppet: '@agoric/swingset-vat/tools/vat-puppet.js',
}),
/** @type {Partial<SwingSetConfig>} */
configOverrides: {
// Aggressive GC.
defaultReapInterval: 1,
Expand Down
2 changes: 2 additions & 0 deletions packages/cosmic-swingset/tools/test-kit.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ const stripUndefined = obj =>
Object.entries(obj).filter(([_key, value]) => value !== undefined),
);

/** @type {InitMsg} */
export const defaultInitMessage = harden(
makeInitMsg({
type: SwingsetMessageType.AG_COSMOS_INIT,
Expand All @@ -59,6 +60,7 @@ export const defaultInitMessage = harden(
),
}),
);
/** @type {InitMsg} */
export const defaultBootstrapMessage = harden({
...deepCopyJsonable(defaultInitMessage),
blockHeight: 1,
Expand Down
3 changes: 0 additions & 3 deletions packages/cosmic-swingset/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
// This file can contain .js-specific Typescript compiler config.
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"checkJs": false,
},
"include": [
"calc-*.js",
"src/**/*.js",
Expand Down
1 change: 1 addition & 0 deletions packages/internal/src/chain-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import * as _ActionType from './action-types.js';
* @typedef {BlockInfo & {
* type: typeof _ActionType.AG_COSMOS_INIT;
* chainID: string;
* isBootstrap?: boolean;
* supplyCoins: { denom: string; amount: NatString }[];
* }} InitMsg
* cosmosInitAction fields that are subject to consensus. See cosmosInitAction
Expand Down
2 changes: 1 addition & 1 deletion packages/swingset-liveslots/src/liveslots.js
Original file line number Diff line number Diff line change
Expand Up @@ -1319,7 +1319,7 @@ function build(

/**
* @param {import('./types.js').VatDeliveryObject} delivery
* @returns {void | Promise<void>}
* @returns {undefined | ReturnType<startVat>}
*/
function dispatchToUserspace(delivery) {
let result;
Expand Down

0 comments on commit a7bee20

Please sign in to comment.