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
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ describe('LogsExtractionClient', () => {
let mockEsClient: jest.Mocked<ElasticsearchClient>;
let mockDataViewsService: jest.Mocked<DataViewsService>;
let mockEngineDescriptorClient: jest.Mocked<
Pick<EngineDescriptorClient, 'findOrThrow' | 'update'>
Pick<EngineDescriptorClient, 'findOrThrow' | 'update' | 'updateWith'>
>;
let mockGlobalStateClient: ReturnType<typeof createMockGlobalStateClient>;
let mockCcsLogsExtractionClient: ReturnType<typeof createMockCcsLogsExtractionClient>;
Expand All @@ -152,6 +152,7 @@ describe('LogsExtractionClient', () => {
mockEngineDescriptorClient = {
findOrThrow: jest.fn(),
update: jest.fn().mockResolvedValue({}),
updateWith: jest.fn().mockResolvedValue({}),
};
mockGlobalStateClient = createMockGlobalStateClient();
mockCcsLogsExtractionClient = createMockCcsLogsExtractionClient();
Expand All @@ -168,6 +169,17 @@ describe('LogsExtractionClient', () => {
});

describe('extractLogs', () => {
function applyLastUpdater(
entityType: EntityType = 'user',
descriptorOverrides?: Partial<Awaited<ReturnType<EngineDescriptorClient['findOrThrow']>>>
) {
const [[, updater]] = mockEngineDescriptorClient.updateWith.mock.calls;
return updater({
...createMockEngineDescriptor(entityType),
...descriptorOverrides,
} as Awaited<ReturnType<EngineDescriptorClient['findOrThrow']>>);
}

it('should successfully extract logs and ingest entities', async () => {
const lastTimestamp = '2024-01-02T12:00:00.000Z';
const mockEsqlResponse: ESQLSearchResponse = {
Expand Down Expand Up @@ -229,20 +241,22 @@ describe('LogsExtractionClient', () => {
abortController: undefined,
});

expect(mockEngineDescriptorClient.update).toHaveBeenCalledWith(
expect(mockEngineDescriptorClient.updateWith).toHaveBeenCalledWith(
'user',
expect.objectContaining({
logExtractionState: expect.objectContaining({
paginationTimestamp: undefined,
paginationId: undefined,
logsPageCursorStartTimestamp: undefined,
logsPageCursorStartId: undefined,
logsPageCursorEndTimestamp: undefined,
logsPageCursorEndId: undefined,
lastExecutionTimestamp: expect.any(String),
}),
})
expect.any(Function)
);
expect(applyLastUpdater()).toMatchObject({
logExtractionState: expect.objectContaining({
paginationTimestamp: undefined,
paginationId: undefined,
logsPageCursorStartTimestamp: undefined,
logsPageCursorStartId: undefined,
logsPageCursorEndTimestamp: undefined,
logsPageCursorEndId: undefined,
lastExecutionTimestamp: expect.any(String),
}),
error: undefined,
});
});

it('should handle empty results from ESQL query', async () => {
Expand All @@ -266,20 +280,22 @@ describe('LogsExtractionClient', () => {

expect(mockExecuteEsqlQuery).toHaveBeenCalledTimes(1);
expect(mockIngestEntities).toHaveBeenCalledTimes(0);
expect(mockEngineDescriptorClient.update).toHaveBeenCalledWith(
expect(mockEngineDescriptorClient.updateWith).toHaveBeenCalledWith(
'user',
expect.objectContaining({
logExtractionState: expect.objectContaining({
paginationTimestamp: undefined,
paginationId: undefined,
logsPageCursorStartTimestamp: undefined,
logsPageCursorStartId: undefined,
logsPageCursorEndTimestamp: undefined,
logsPageCursorEndId: undefined,
lastExecutionTimestamp: expect.any(String),
}),
})
expect.any(Function)
);
expect(applyLastUpdater()).toMatchObject({
logExtractionState: expect.objectContaining({
paginationTimestamp: undefined,
paginationId: undefined,
logsPageCursorStartTimestamp: undefined,
logsPageCursorStartId: undefined,
logsPageCursorEndTimestamp: undefined,
logsPageCursorEndId: undefined,
lastExecutionTimestamp: expect.any(String),
}),
error: undefined,
});
});

it('should compute extraction window from lookbackPeriod and delay when no custom range', async () => {
Expand Down Expand Up @@ -538,7 +554,7 @@ describe('LogsExtractionClient', () => {
esClient: mockEsClient,
query: expect.stringContaining(toDate),
});
expect(mockEngineDescriptorClient.update).not.toHaveBeenCalled();
expect(mockEngineDescriptorClient.updateWith).not.toHaveBeenCalled();
});

it('should not update engine descriptor when specificWindow is provided', async () => {
Expand Down Expand Up @@ -577,7 +593,7 @@ describe('LogsExtractionClient', () => {
expect(result.success && result.count).toBe(2);
expect(mockExecuteEsqlQuery).toHaveBeenCalledTimes(3);
expect(mockIngestEntities).toHaveBeenCalledTimes(1);
expect(mockEngineDescriptorClient.update).not.toHaveBeenCalled();
expect(mockEngineDescriptorClient.updateWith).not.toHaveBeenCalled();
});

it('should handle errors from executeEsqlQuery', async () => {
Expand Down Expand Up @@ -720,21 +736,48 @@ describe('LogsExtractionClient', () => {
expect(mockIngestEntities).toHaveBeenCalledTimes(1);

// CCS error is stored in the saved object
expect(mockEngineDescriptorClient.update).toHaveBeenCalledWith(
expect(mockEngineDescriptorClient.updateWith).toHaveBeenCalledWith(
'user',
expect.objectContaining({
logExtractionState: expect.objectContaining({
paginationTimestamp: undefined,
paginationId: undefined,
logsPageCursorStartTimestamp: undefined,
logsPageCursorStartId: undefined,
logsPageCursorEndTimestamp: undefined,
logsPageCursorEndId: undefined,
lastExecutionTimestamp: expect.any(String),
}),
error: { message: ccsError.message, action: 'extractLogs' },
})
expect.any(Function)
);
expect(applyLastUpdater()).toMatchObject({
logExtractionState: expect.objectContaining({
paginationTimestamp: undefined,
paginationId: undefined,
logsPageCursorStartTimestamp: undefined,
logsPageCursorStartId: undefined,
logsPageCursorEndTimestamp: undefined,
logsPageCursorEndId: undefined,
lastExecutionTimestamp: expect.any(String),
}),
error: { message: ccsError.message, action: 'extractLogs' },
});
});

it('should clear a previous error after a successful extraction', async () => {
const mockDataView = {
getIndexPattern: jest.fn().mockReturnValue('logs-*'),
};

mockEngineDescriptorClient.findOrThrow.mockResolvedValue(
createMockEngineDescriptor('user') as Awaited<
ReturnType<EngineDescriptorClient['findOrThrow']>
>
);
mockDataViewsService.get.mockResolvedValue(mockDataView as any);
mockExecuteEsqlQuery.mockResolvedValue(mockLogPaginationCursorProbeEmpty());
mockIngestEntities.mockResolvedValue(undefined);

await client.extractLogs('user');

expect(mockEngineDescriptorClient.updateWith).toHaveBeenCalledWith(
'user',
expect.any(Function)
);
expect(
applyLastUpdater('user', { error: { message: 'previous error', action: 'extractLogs' } })
.error
).toBeUndefined();
});

it('should fallback to logs-* when data view is not found', async () => {
Expand Down Expand Up @@ -787,20 +830,21 @@ describe('LogsExtractionClient', () => {
targetIndex: expect.stringContaining('.entities.v2.latest.security_default'),
})
);
expect(mockEngineDescriptorClient.update).toHaveBeenCalledWith(
expect(mockEngineDescriptorClient.updateWith).toHaveBeenCalledWith(
'host',
expect.objectContaining({
logExtractionState: expect.objectContaining({
paginationTimestamp: undefined,
paginationId: undefined,
logsPageCursorStartTimestamp: undefined,
logsPageCursorStartId: undefined,
logsPageCursorEndTimestamp: undefined,
logsPageCursorEndId: undefined,
lastExecutionTimestamp: expect.any(String),
}),
})
expect.any(Function)
);
expect(applyLastUpdater('host')).toMatchObject({
logExtractionState: expect.objectContaining({
paginationTimestamp: undefined,
paginationId: undefined,
logsPageCursorStartTimestamp: undefined,
logsPageCursorStartId: undefined,
logsPageCursorEndTimestamp: undefined,
logsPageCursorEndId: undefined,
lastExecutionTimestamp: expect.any(String),
}),
});
});

it('should return success false when engine is not started', async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,8 @@ export class LogsExtractionClient {
return operationResult;
}

await this.engineDescriptorClient.update(type, {
await this.engineDescriptorClient.updateWith(type, (current) => ({
...current,
logExtractionState: {
// we went through all the pages,
// therefore we can leave the lastExecutionTimestamp as the beginning of the next
Expand All @@ -170,7 +171,7 @@ export class LogsExtractionClient {
lastExecutionTimestamp: lastSearchTimestamp || moment().utc().toISOString(),
},
error: ccsError ? { message: ccsError.message, action: 'extractLogs' } : undefined,
});
}));

return operationResult;
} catch (error) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,22 @@ export class EngineDescriptorClient {
return attributes;
}

async updateWith(
entityType: EntityType,
updater: (current: EngineDescriptor) => EngineDescriptor
): Promise<EngineDescriptor> {
const current = await this.findOrThrow(entityType);
const updated = updater(current);
const id = this.getSavedObjectId(entityType);
const { attributes } = await this.soClient.update<EngineDescriptor>(
Comment on lines +83 to +86
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We have a potential race condition here, any concurrent change to the SO between findOrThrow() and update() can be lost (a call to the entity store management api updates the SO).
I consider it as minor, but something we should be aware of.
The right way to overcome this race would be by optimistic concurrency, adding the SO version to the update call, a conflict will be thrown in case there were an additional update between our read-write operation.

Example:

  public async get(
    id: string,
    spaceId?: string
  ): Promise<{ id: string; attributes: RuleSavedObjectAttributes; version?: string }> {
    const namespace = spaceIdToNamespace(this.spaces, spaceId);
    const doc = await this.client.get<RuleSavedObjectAttributes>(
      RULE_SAVED_OBJECT_TYPE,
      id,
      namespace ? { namespace } : undefined
    );
    return { id: doc.id, attributes: doc.attributes, version: doc.version };
  }
  public async update({
    id,
    attrs,
    version,
  }: {
    id: string;
    attrs: RuleSavedObjectAttributes;
    version?: string;
  }): Promise<void> {
    await this.client.update<RuleSavedObjectAttributes>(RULE_SAVED_OBJECT_TYPE, id, attrs, {
      ...(version ? { version } : {}),
      mergeAttributes: false,
    });
  }

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is the same for our regular update not just the newly added updateWith

doc.version seems like a nice addition we should add anyway, even if this specifically is hardly an issue

EngineDescriptorTypeName,
id,
updated,
{ refresh: 'wait_for', mergeAttributes: false }
);
return attributes as EngineDescriptor;
}

async update(
entityType: EntityType,
state: Partial<EngineDescriptor>,
Expand Down
Loading