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
92 changes: 92 additions & 0 deletions scopes/scope/objects/objects/repository.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { expect } from 'chai';
import fs from 'fs-extra';
import os from 'os';
import path from 'path';
import zlib from 'zlib';
import { ScopeJson } from '@teambit/legacy.scope';
import { ModelComponent, Source } from '../models';
import Ref from './ref';
import Repository from './repository';
import { IndexType } from './scope-index';

const SCOPE_NAME = 'my-scope';
const SOURCES_COUNT = 5;

/**
* `Repository.list(types)` is what rebuilds a missing `index.json`, and it's asked for a handful of
* object types in a scope that is mostly file contents. the type is in each file's header, so the
* rest of a file should only be read when its type is one that was asked for.
*/
describe('Repository.list', () => {
let scopePath: string;
let scopeJson: ScopeJson;
let repository: Repository;
let contentReads: number;
const original = {
onPostObjectRead: Repository.onPostObjectRead,
hasPostObjectReadTransformer: Repository.hasPostObjectReadTransformer,
};

beforeEach(async () => {
scopePath = await fs.mkdtemp(path.join(os.tmpdir(), 'bit-repository-spec-'));
scopeJson = new ScopeJson(
{ name: SCOPE_NAME, version: '1.0.0', groupName: null },
path.join(scopePath, 'scope.json')
);
repository = await Repository.create({ scopePath, scopeJson });
const modelComponent = ModelComponent.from({
name: 'bar/foo',
scope: SCOPE_NAME,
lang: 'javascript',
deprecated: false,
bindingPrefix: '@bit',
versions: {},
});
const sources = Array.from({ length: SOURCES_COUNT }, (_, i) => Source.from(Buffer.from(`file ${i}`)));
const objects = [modelComponent, ...sources];
objects.forEach((object) => {
object.validateBeforePersist = false;
});
await repository.writeObjectsToTheFS(objects);

contentReads = 0;
// every full read of an object file goes through this hook, while a header read doesn't
Repository.onPostObjectRead = (content) => {
contentReads += 1;
return content;
};
});

afterEach(async () => {
Repository.onPostObjectRead = original.onPostObjectRead;
Repository.hasPostObjectReadTransformer = original.hasPostObjectReadTransformer;
await fs.remove(scopePath);
});

it('should rebuild a missing index.json reading the contents of the wanted objects only', async () => {
Repository.hasPostObjectReadTransformer = () => false;
await Repository.reset(scopePath);
const loaded = await Repository.load({ scopePath, scopeJson });
expect(loaded.scopeIndex.getHashes(IndexType.components)).to.have.lengthOf(1);
expect(contentReads).to.equal(1);
});

it('should read every object once when a transformer is registered, as the header is transformed too', async () => {
Repository.hasPostObjectReadTransformer = () => true;
const objects = await repository.list([ModelComponent]);
expect(objects).to.have.lengthOf(1);
expect(contentReads).to.equal(SOURCES_COUNT + 1);
});

it('should skip an object whose header names a type nothing is registered under, as the full read does', async () => {
Repository.hasPostObjectReadTransformer = () => false;
const hash = 'a'.repeat(40);
const content = 'whatever';
const unknownObject = zlib.deflateSync(Buffer.from(`NotARealType ${hash} ${content.length}\0${content}`));
const objectPath = repository.objectPath(Ref.from(hash));
await fs.outputFile(objectPath, unknownObject);
const objects = await repository.list([ModelComponent]);
expect(objects).to.have.lengthOf(1);
expect(objects[0]).to.be.instanceOf(ModelComponent);
});
});
62 changes: 47 additions & 15 deletions scopes/scope/objects/objects/repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,13 @@ import { glob } from 'glob';
import { removeEmptyDir } from '@teambit/toolbox.fs.remove-empty-dir';
import { concurrentIOLimit } from '@teambit/harmony.modules.concurrency';
import type { Types, ScopeJson } from '@teambit/legacy.scope';
import { HashNotFound, OutdatedIndexJson, UnmergedComponents, RemoteLanes } from '@teambit/legacy.scope';
import {
HashNotFound,
OutdatedIndexJson,
UnknownObjectType,
UnmergedComponents,
RemoteLanes,
} from '@teambit/legacy.scope';
import type { IndexType, IndexItem } from './scope-index';
import { ScopeIndex } from './scope-index';
import BitObject from './object';
Expand Down Expand Up @@ -311,32 +317,46 @@ export default class Repository {
const objectPath = this.objectPath(ref);
try {
const stat = await fs.stat(objectPath);
const type = await this.readObjectType(objectPath, stat.size);
const type = await this.readObjectType(objectPath);
return { object: { ref, type, size: stat.size, mtimeMs: stat.mtimeMs } };
} catch (err: any) {
logger.warn(`Repository.listObjectsWithType, failed reading ${objectPath}. Error: ${err.message}`);
return { unreadable: ref };
}
}

private async readObjectType(objectPath: string, size: number): Promise<string> {
private async readObjectType(objectPath: string): Promise<string> {
const readInFull = async () => BitObject.parseObjectType(this.onRead(await fs.readFile(objectPath)), objectPath);
// when there's no way to tell, assume the content is transformed and read in full. it's the
// slow answer, never the wrong one.
const isTransformed = Repository.hasPostObjectReadTransformer
if (this.isContentTransformed()) return readInFull();
return (await this.readTypeFromHeader(objectPath)) || readInFull();
}

/**
* whether object files have to go through `onPostObjectRead` before their header can be read.
* when there's no way to tell, assume they do. it's the slow answer, never the wrong one.
*/
private isContentTransformed(): boolean {
return Repository.hasPostObjectReadTransformer
? Repository.hasPostObjectReadTransformer()
: Boolean(Repository.onPostObjectRead);
if (isTransformed) return readInFull();
const chunkSize = Math.min(OBJECT_HEADER_CHUNK_SIZE, size);
}

/**
* the type an object file names in its header, read from the first chunk of the file only.
* null when that chunk doesn't hold the whole header, in which case the file has to be read in
* full. throws `UnknownObjectType` when the header names a type nothing is registered under.
*/
private async readTypeFromHeader(objectPath: string): Promise<string | null> {
// `Uint8Array` rather than `Buffer` - see `parseObjectTypeFromChunk`
const chunk = new Uint8Array(chunkSize);
const chunk = new Uint8Array(OBJECT_HEADER_CHUNK_SIZE);
const fileDescriptor = await fs.open(objectPath, 'r');
let bytesRead: number;
try {
await fs.read(fileDescriptor, chunk, 0, chunkSize, 0);
({ bytesRead } = await fs.read(fileDescriptor, chunk, 0, chunk.length, 0));
} finally {
await fs.close(fileDescriptor);
}
return BitObject.parseObjectTypeFromChunk(chunk) || readInFull();
return BitObject.parseObjectTypeFromChunk(chunk.subarray(0, bytesRead));
}

async loadRefDeleteIfInvalid(ref: Ref) {
Expand All @@ -356,11 +376,23 @@ export default class Repository {

async loadRefOnlyIfType(ref: Ref, types: Types): Promise<BitObject | null> {
const objectPath = this.objectPath(ref);
const fileContentsRaw = await fs.readFile(objectPath);
const fileContents = this.onRead(fileContentsRaw);
const typeNames = types.map((type) => type.name);
const parsedObject = await BitObject.parseObjectOnlyIfType(fileContents, typeNames, objectPath);
return parsedObject;
// most of a scope is file contents, which callers of this never ask for. the header says
// whether an object is wanted, so the rest of the file is only read and inflated when it is.
// transformed content has no header to read on its own, so it keeps to the single full read.
if (!this.isContentTransformed()) {
let type: string | null;
try {
type = await this.readTypeFromHeader(objectPath);
} catch (err: any) {
// an unregistered type is not one of the types asked for - the same answer the full read gives
if (err instanceof UnknownObjectType) return null;
throw err;
}
if (type && !typeNames.includes(type)) return null;
}
const fileContents = this.onRead(await fs.readFile(objectPath));
return BitObject.parseObjectOnlyIfType(fileContents, typeNames, objectPath);
}

async listRefs(cwd = this.getPath()): Promise<Array<Ref>> {
Expand Down
Loading