Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 81 additions & 0 deletions scopes/envs/envs/environments.main.runtime.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { expect } from 'chai';
import { loadAspect } from '@teambit/harmony.testing.load-aspect';
import type { WorkspaceData } from '@teambit/workspace.testing.mock-workspace';
import { mockWorkspace, destroyWorkspace } from '@teambit/workspace.testing.mock-workspace';
import { ComponentID } from '@teambit/component-id';
import type { Component } from '@teambit/component';
import type { EnvsMain } from './environments.main.runtime';
import { EnvsAspect } from './environments.aspect';

/**
* a component configured with an env that is not registered in the envs slot. that's the state
* that makes `calculateEnv` consider warning "env was not loaded (run bit install)".
*/
function mockComponentWithUnregisteredEnv(componentId: string, envId: string): Component {
return {
id: ComponentID.fromString(componentId),
state: {
aspects: {
get: (aspectId: string) => (aspectId === EnvsAspect.id ? { config: { env: envId } } : undefined),
entries: [{ id: ComponentID.fromString(envId) }],
},
},
} as unknown as Component;
}

describe('EnvsMain', function () {
this.timeout(0);
let workspaceData: WorkspaceData;
let envs: EnvsMain;
before(async () => {
workspaceData = mockWorkspace();
envs = await loadAspect(EnvsAspect, workspaceData.workspacePath);
});
after(async () => {
await destroyWorkspace(workspaceData);
});

describe('skipNotLoadedWarnings', () => {
// the env landing in "failed to load envs" is the observable side effect of the warning.
it('should not report the env as failed-to-load when muted', async () => {
const envId = 'some-scope/envs/[email protected]';
const component = mockComponentWithUnregisteredEnv('some-scope/comps/[email protected]', envId);
await envs.skipNotLoadedWarnings(async () => {
envs.calculateEnv(component);
});
expect(envs.getFailedToLoadEnvs()).to.not.include(envId);
});

it('should report the env as failed-to-load when not muted', async () => {
const envId = 'some-scope/envs/[email protected]';
const component = mockComponentWithUnregisteredEnv('some-scope/comps/[email protected]', envId);
envs.calculateEnv(component);
expect(envs.getFailedToLoadEnvs()).to.include(envId);
});

it('should not mute a calculation running outside the scope while a scope is open', async () => {
const envId = 'some-scope/envs/[email protected]';
const component = mockComponentWithUnregisteredEnv('some-scope/comps/[email protected]', envId);
// the scope stays open until the next macrotask, so calculateEnv below runs while it's open
const openScope = envs.skipNotLoadedWarnings(() => new Promise<void>((resolve) => setImmediate(resolve)));
envs.calculateEnv(component);
await openScope;
expect(envs.getFailedToLoadEnvs()).to.include(envId);
});

it('should stop muting once the scope ends, including when it throws', async () => {
const envId = 'some-scope/envs/[email protected]';
const component = mockComponentWithUnregisteredEnv('some-scope/comps/[email protected]', envId);
try {
await envs.skipNotLoadedWarnings(async () => {
throw new Error('some error');
});
expect.fail('should have thrown');
} catch (err: any) {
expect(err.message).to.equal('some error');
}
envs.calculateEnv(component);
expect(envs.getFailedToLoadEnvs()).to.include(envId);
});
});
});
31 changes: 30 additions & 1 deletion scopes/envs/envs/environments.main.runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { head, uniq } from 'lodash';
import type { WorkerMain } from '@teambit/worker';
import { WorkerAspect } from '@teambit/worker';
import { ComponentID } from '@teambit/component-id';
import { AsyncLocalStorage } from 'async_hooks';
import type { EnvService } from './services';
import type { Environment } from './environment';
import { EnvsAspect } from './environments.aspect';
Expand Down Expand Up @@ -120,6 +121,8 @@ export class EnvsMain {
* Ids of envs (not neccesrraly loaded successfully)
*/
public envIds = new Set<string>();
/** set inside a `skipNotLoadedWarnings` scope. see that method. */
private notLoadedWarningsMuted = new AsyncLocalStorage<true>();

static runtime = MainRuntime;

Expand Down Expand Up @@ -208,6 +211,32 @@ export class EnvsMain {
this.failedToLoadExt.clear();
}

/**
* run `fn` with the "env was not loaded" warnings muted.
*
* the workspace loads components in groups, and one of those groups holds components that are
* loaded only so they can be registered as the env of another component. the env of *those*
* components (the env-of-env) is scheduled only when the env component itself is one of the
* requested ids, so during that pass an unregistered env says nothing about whether it's
* installed - warning about it is a false positive. e.g. "bit show <comp>" used to report that
* the env of <comp>'s env "was not loaded (run bit install)" on a perfectly healthy workspace.
*
* this is a scope rather than a param because the warning is reached from many aspects that
* calculate the env during the load slot (tester, docs, pkg, compositions, dev-files), so muting
* a single call site only moves the warning to the next one. it is execution-local rather than a
* field because loads run concurrently (the graphql resolver fans ids out with Promise.all), and
* a shared flag would let one load mute an unrelated one and hide a genuinely missing env.
*/
async skipNotLoadedWarnings<T>(fn: () => Promise<T>): Promise<T> {
// the promise is created inside run() so the whole execution of `fn` is within the scope.
// (assigned via `let` because some @types/node versions type `run` as returning void)
let promise!: Promise<T>;
this.notLoadedWarningsMuted.run(true, () => {
promise = fn();
});
return promise;
}

getFailedToLoadEnvs() {
const failedToLoadEnvs = Array.from(this.failedToLoadEnvs);
// Add all extensions which are also envs
Expand Down Expand Up @@ -704,7 +733,7 @@ export class EnvsMain {
this.envIds.add(envDef.id);
return envDef;
}
if (!opts.skipWarnings) {
if (!opts.skipWarnings && !this.notLoadedWarningsMuted.getStore()) {
// Do not allow a non existing env
this.printWarningIfFirstTime(
matchedEntry.id.toString(),
Expand Down
16 changes: 15 additions & 1 deletion scopes/workspace/install/install.main.runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,10 @@ export class InstallMain {
}
}

// set workspace in install context
// set workspace in install context. `_installModules` sets these too, but the work below it
// (_addPackages, the preInstallSlot) already runs as part of the installation, and a stale
// "after package manager" flag from an earlier install in this process would let it compile
// against the pre-install dependency state.
this.workspace.inInstallContext = true;
this.workspace.inInstallAfterPmContext = false;
if (packages && packages.length) {
Expand Down Expand Up @@ -362,11 +365,22 @@ export class InstallMain {
}

private async _installModules(options?: ModulesInstallOptions): Promise<ComponentMap<string>> {
// components are loaded here before the envs are loaded as aspects, so envs legitimately appear
// "not loaded" while this runs. every caller is by definition running an installation, so the
// flags that mute those premature warnings belong here rather than at each entry point - an
// entry point that forgot them reported "env was not loaded (run bit install)" on a healthy
// workspace, while itself running the very install it suggested.
const prevInInstallContext = this.workspace.inInstallContext;
const prevInInstallAfterPmContext = this.workspace.inInstallAfterPmContext;
this.workspace.inInstallContext = true;
this.workspace.inInstallAfterPmContext = false;
this.logger.profile('install.total');
try {
return await this._installModulesProfiled(options);
} finally {
this.logger.profile('install.total');
this.workspace.inInstallContext = prevInInstallContext;
this.workspace.inInstallAfterPmContext = prevInInstallAfterPmContext;
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { expect } from 'chai';
import { ComponentID } from '@teambit/component-id';
import { isRequestedId } from './workspace-component-loader';

/**
* the predicate decides whether a component is loaded because the caller asked for it, or only
* because a requested component uses it as an aspect/env. the loader mutes the "env was not loaded"
* warning for the latter, so a mismatch here either hides a real warning or brings the false one
* back. it must not be confused with a load group's `seeders` flag, which marks which components
* are returned to the caller - groups built from extension ids carry `seeders: true` as well.
*/
describe('isRequestedId', () => {
const requested = (...ids: string[]) =>
new Set(ids.flatMap((id) => [id, ComponentID.fromString(id).toStringWithoutVersion()]));

it('should treat an id the caller asked for as requested', () => {
const ids = requested('some-scope/comps/[email protected]');
expect(isRequestedId(ComponentID.fromString('some-scope/comps/[email protected]'), ids)).to.be.true;
});

it('should treat an id the caller did not ask for as not requested', () => {
const ids = requested('some-scope/comps/[email protected]');
expect(isRequestedId(ComponentID.fromString('some-scope/envs/[email protected]'), ids)).to.be.false;
});

// the requested ids and the loaded component can disagree on the version, e.g. when the id was
// given without one. erring towards "requested" keeps the warning rather than muting it.
it('should treat a different version of a requested id as requested', () => {
const ids = requested('some-scope/comps/[email protected]');
expect(isRequestedId(ComponentID.fromString('some-scope/comps/[email protected]'), ids)).to.be.true;
});

it('should treat everything as requested when the requested set is unknown', () => {
expect(isRequestedId(ComponentID.fromString('some-scope/comps/[email protected]'))).to.be.true;
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,14 @@ type LoadGroupMetadata = {
envs?: boolean;
};

type GetAndLoadSlotOpts = ComponentLoadOptions & LoadGroupMetadata;
type GetAndLoadSlotOpts = ComponentLoadOptions &
LoadGroupMetadata & {
/**
* ids the caller asked for, in both their versioned and unversioned form. anything else in the
* group is loaded only because a requested component uses it as an aspect/env.
*/
requestedIds?: Set<string>;
};

type ComponentGetOneOptions = {
resolveIdVersion?: boolean;
Expand Down Expand Up @@ -218,6 +225,9 @@ export class WorkspaceComponentLoader {
this.logger.profileTrace('buildLoadGroups');
const groupsToHandle = await loadSpan('build-load-groups', {}, () => this.buildLoadGroups(workspaceScopeIdsMap));
this.logger.profileTrace('buildLoadGroups');
// both forms, so that a component is treated as requested whenever there is any doubt - erring
// towards warning rather than towards muting. see the `executeLoadSlot` call in getAndLoadSlot.
const requestedIds = new Set(ids.flatMap((id) => [id.toString(), id.toStringWithoutVersion()]));
// prefix your command with "BIT_LOG=*" to see the detailed groups
if (process.env.BIT_LOG) {
printGroupsToHandle(groupsToHandle, this.logger);
Expand All @@ -234,7 +244,7 @@ export class WorkspaceComponentLoader {
const res = await loadSpan(
'load-group',
{ group: `${index + 1}/${groupsToHandle.length}`, desc: groupStr },
() => this.getAndLoadSlot(workspaceIds, scopeIds, { ...loadOpts, core, seeders, aspects, envs })
() => this.getAndLoadSlot(workspaceIds, scopeIds, { ...loadOpts, core, seeders, aspects, envs, requestedIds })
);
this.logger.profileTrace(groupDesc);
// We don't want to return components that were not asked originally (we do want to load them)
Expand Down Expand Up @@ -460,9 +470,19 @@ export class WorkspaceComponentLoader {
let wsComponentsWithAspects = workspaceComponents;
// if (loadOpts.seeders) {
this.logger.profileTrace('executeLoadSlot');
wsComponentsWithAspects = await pMapPool(workspaceComponents, (component) => this.executeLoadSlot(component), {
concurrency: concurrentComponentsLimit(),
});
wsComponentsWithAspects = await pMapPool(
workspaceComponents,
(component) => {
// a component nobody asked for is here only because a requested component uses it as an
// aspect/env. its own env (the env-of-env) is never scheduled for this load, so finding it
// unregistered says nothing about whether it's installed. see EnvsMain.skipNotLoadedWarnings.
if (isRequestedId(component.id, loadOpts.requestedIds)) return this.executeLoadSlot(component);
return this.envs.skipNotLoadedWarnings(() => this.executeLoadSlot(component));
},
{
concurrency: concurrentComponentsLimit(),
}
);
this.logger.profileTrace('executeLoadSlot');
await this.warnAboutMisconfiguredEnvs(wsComponentsWithAspects);
// }
Expand Down Expand Up @@ -1227,6 +1247,16 @@ export class WorkspaceComponentLoader {
}
}

/**
* whether the caller asked for this id, as opposed to it being pulled in as another component's
* aspect/env. matches both the versioned and unversioned form, and treats an unknown requested-set
* as "everything was requested", so an unexpected call path warns rather than silently mutes.
*/
export function isRequestedId(id: ComponentID, requestedIds?: Set<string>): boolean {
if (!requestedIds) return true;
return requestedIds.has(id.toString()) || requestedIds.has(id.toStringWithoutVersion());
}

function createComponentCacheKey(id: ComponentID, loadOpts?: ComponentLoadOptions): string {
const relevantOpts = pick(loadOpts, ['loadExtensions', 'executeLoadSlot', 'loadDocs', 'loadCompositions']);
return `${id.toString()}:${JSON.stringify(sortKeys(relevantOpts ?? {}))}`;
Expand Down
Loading