Skip to content

Commit

Permalink
Merge pull request #2498 from demergent-labs/harmonize_init_and_post_…
Browse files Browse the repository at this point in the history
…upgrade_1095

Harmonize init and post upgrade
  • Loading branch information
lastmjs authored Jan 21, 2025
2 parents 1873b8d + d317305 commit 99c653c
Show file tree
Hide file tree
Showing 12 changed files with 281 additions and 132 deletions.
21 changes: 10 additions & 11 deletions .github/actions/get_test_infos/discover_test_dirs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,24 @@ import { join } from 'path';

// Recursively find directories and check for package.json with a test script
export async function discoverTestDirs(dirToSearch: string): Promise<string[]> {
// Check the root directory first
const hasTestScript = await checkForTestScript(
join(dirToSearch, 'package.json')
);
if (hasTestScript === true) {
return [dirToSearch];
}

// If no test script found, check subdirectories
const files = await readdir(dirToSearch, { withFileTypes: true });

return files.reduce(
async (accPromise, file) => {
const acc = await accPromise;

const fullPath = join(dirToSearch, file.name);

if (file.isDirectory() && !fullPath.includes('node_modules')) {
// Check for package.json and if it contains a test script
const packageJsonPath = join(fullPath, 'package.json');
const hasTestScript = await checkForTestScript(packageJsonPath);

// Recurse into subdirectory
return [
...acc,
...(hasTestScript ? [fullPath] : []),
...(await discoverTestDirs(fullPath))
];
return [...acc, ...(await discoverTestDirs(fullPath))];
}

return acc;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export function getTests(canisterName: string): Test {
browser = await puppeteer.launch({
headless:
process.env.GITHUB_RUN_ID === undefined ? false : true,
args: ['--no-sandbox', '--disable-setuid-sandbox']
args: ['--no-sandbox']
});
page = await browser.newPage();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export function getTests(canisterName: string): Test {
return () => {
it('supports internet identity authentication', async () => {
const browser = await puppeteer.launch({
args: ['--no-sandbox', '--disable-setuid-sandbox']
args: ['--no-sandbox']
});
const page = await browser.newPage();

Expand Down
8 changes: 4 additions & 4 deletions src/build/experimental/commands/compile/javascript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export function getPrelude(main: string): string {
import { ethers } from 'ethers';
ethers.FetchRequest.registerGetUrl(ethersGetUrl);
import { DidVisitor, getDefaultVisitorData, IDL, toDidString } from 'azle';
import { getDefaultVisitorData, IDL, idlToString } from 'azle';
export { Principal } from '@dfinity/principal';
import * as Canister from './${main}';
Expand Down Expand Up @@ -81,17 +81,17 @@ export function getPrelude(main: string): string {
}, {});
}
const candid = canister.getIdlType([]).accept(new DidVisitor(), {
const candid = idlToString(canister.getIdlType([]), {
...getDefaultVisitorData(),
isFirstService: true,
systemFuncs: canister.getSystemFunctionIdlTypes()
initAndPostUpgradeParamIdlTypes: canister.getInitAndPostUpgradeParamIdlTypes()
});
globalThis._azleCallbacks = canister.callbacks;
globalThis._azleGetCandidAndMethodMeta = () => {
return JSON.stringify({
candid: toDidString(candid),
candid,
methodMeta: canister.methodMeta
});
};
Expand Down
18 changes: 9 additions & 9 deletions src/build/stable/commands/compile/javascript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ function getPrelude(main: string): string {
return /*TS*/ `
import 'azle/src/lib/stable/globals';
import { DidVisitor, getDefaultVisitorData, IDL, toDidString } from 'azle';
import { getDefaultVisitorData, IDL, idlToString } from 'azle';
import * as Canister from './${main}';
Expand All @@ -27,23 +27,23 @@ export function handleClassApiCanister(): string {
return /*TS*/ `
const exportedCanisterClassInstance = getExportedCanisterClassInstance();
const canisterIdlType = IDL.Service(exportedCanisterClassInstance._azleCanisterMethodIdlTypes);
const candid = canisterIdlType.accept(new DidVisitor(), {
const canisterIdlType = IDL.Service(exportedCanisterClassInstance._azleCanisterMethodIdlParamTypes);
const candid = idlToString(canisterIdlType, {
...getDefaultVisitorData(),
isFirstService: true,
systemFuncs: exportedCanisterClassInstance._azleInitAndPostUpgradeIdlTypes
initAndPostUpgradeParamIdlTypes: exportedCanisterClassInstance._azleInitAndPostUpgradeIdlTypes
});
globalThis._azleGetCandidAndMethodMeta = () => {
return JSON.stringify({
candid: toDidString(candid),
candid,
methodMeta: exportedCanisterClassInstance._azleMethodMeta
});
};
/**
* @internal
*
*
* This function is designed with a very specific purpose.
* We need to get the _azle properties off of this class instance to use in generating the candid
* and method meta information. But we can't just set the result of instantiating the class to a local variable.
Expand All @@ -61,7 +61,7 @@ export function handleClassApiCanister(): string {
* This callback occurs before the class's constructor or properties are initialized.
* There may be some rare conditions where this scheme will not work, but we believe the likelihood is extremely low.
*/
function getExportedCanisterClassInstance() {
function getExportedCanisterClassInstance() {
try {
Canister.default.prototype._azleShouldRegisterCanisterMethods = true;
new Canister.default();
Expand All @@ -76,7 +76,7 @@ export function handleClassApiCanister(): string {
throw error;
}
}
return globalThis._azleExportedCanisterClassInstance;
}
`;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@ import {
Method,
MethodMeta
} from '../../../../../../../build/stable/utils/types';
import { CanisterMethodMode } from '../../../../../../stable/execute_with_candid_serde';
import { CanisterMethodInfo } from '../../../../../canister_methods/types/canister_method_info';
import { Callbacks } from '../../../../../globals';
import { ic } from '../../../../../ic';
import { CandidType, Parent, toIdlTypeArray } from '../../../../index';
import { _AzleRecursiveFunction } from '../../../../recursive';
import { decode, encode } from '../../../../serde';
import { Principal } from '../../principal';
import { createGetSystemFunctionIdlTypeFunction } from './system_methods';
import { createGetInitAndPostUpgradeParamIdlTypes } from './system_methods';

export type CanisterOptions = {
[key: string]: CanisterMethodInfo<any, any>;
Expand All @@ -23,15 +24,15 @@ type _AzleFunctionReturnType = {
(principal: Principal): void;
methodMeta?: MethodMeta;
callbacks?: any;
getSystemFunctionIdlTypes?: (parents: Parent[]) => IDL.FuncClass[];
getInitAndPostUpgradeParamIdlTypes?: (parents: Parent[]) => IDL.Type[];
getIdlType?: (parents: Parent[]) => IDL.Type<any>;
};

type CallRawFunction = typeof ic.callRaw;
type NotifyRawFunction = typeof ic.notifyRaw;

type FunctionInfo = {
mode: 'query' | 'update';
mode: CanisterMethodMode;
paramCandidTypes: CandidType[];
returnCandidType: CandidType;
};
Expand Down Expand Up @@ -59,8 +60,8 @@ export function createCanisterFunction(
canister.methodMeta = methodMeta;

canister.getIdlType = createGetIdlTypeFunction(canisterOptions);
canister.getSystemFunctionIdlTypes =
createGetSystemFunctionIdlTypeFunction(canisterOptions);
canister.getInitAndPostUpgradeParamIdlTypes =
createGetInitAndPostUpgradeParamIdlTypes(canisterOptions);

return canister;
}
Expand Down Expand Up @@ -97,7 +98,7 @@ function createGetIdlTypeFunction(
};
}

function createAnnotation(mode: 'query' | 'update'): string[] {
function createAnnotation(mode: CanisterMethodMode): string[] {
if (mode === 'query') {
return ['query'];
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,39 +2,59 @@ import '../../../../../experimental';

import { IDL } from '@dfinity/candid';

import { idlToString } from '../../../../../../stable/did_file/idl_to_string';
import { Parent, toIdlTypeArray } from '../../../../index';
import { _AzleRecursiveFunction } from '../../../../recursive';
import { CanisterOptions, ServiceFunctionInfo } from '.';

export function createGetSystemFunctionIdlTypeFunction(
export function createGetInitAndPostUpgradeParamIdlTypes(
canisterOptions: CanisterOptions
) {
return (parents: Parent[]): IDL.FuncClass[] => {
return (parents: Parent[]): IDL.Type[] => {
const serviceFunctionInfo = canisterOptions as ServiceFunctionInfo;

return Object.entries(serviceFunctionInfo).reduce(
(accumulator, [_methodName, functionInfo]) => {
const mode = functionInfo.mode;
const isSystemMethod = !(mode === 'update' || mode === 'query');
if (!isSystemMethod) {
// IDLs that are in update and query are already accounted for in the standard getIdlType function
return accumulator;
}

const paramIdlTypes = toIdlTypeArray(
functionInfo.paramCandidTypes,
parents
);
const returnIdlType = toIdlTypeArray(
functionInfo.returnCandidType,
parents
);
return [
...accumulator,
IDL.Func(paramIdlTypes, returnIdlType, [mode])
];
},
[] as IDL.FuncClass[]
const initMethod = Object.entries(serviceFunctionInfo).find(
([_, info]) => info.mode === 'init'
);
const postUpgradeMethod = Object.entries(serviceFunctionInfo).find(
([_, info]) => info.mode === 'postUpgrade'
);

if (initMethod !== undefined && postUpgradeMethod !== undefined) {
const initParams = toIdlTypeArray(
initMethod[1].paramCandidTypes,
parents
);
const postUpgradeParams = toIdlTypeArray(
postUpgradeMethod[1].paramCandidTypes,
parents
);

const initSignature = idlToString(IDL.Func(initParams, []));
const postUpgradeSignature = idlToString(
IDL.Func(postUpgradeParams, [])
);

if (initSignature !== postUpgradeSignature) {
throw new Error(
`'@init' and '@postUpgrade' methods must have the same parameters.\nFound:\n${initSignature}\n${postUpgradeSignature}`
);
}

return initParams;
}

if (initMethod !== undefined) {
return toIdlTypeArray(initMethod[1].paramCandidTypes, parents);
}

if (postUpgradeMethod !== undefined) {
return toIdlTypeArray(
postUpgradeMethod[1].paramCandidTypes,
parents
);
}

return [];
};
}
Loading

0 comments on commit 99c653c

Please sign in to comment.