-
Notifications
You must be signed in to change notification settings - Fork 23
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(docs): move algolia data ingestion to docs-tools #2239
Closed
Closed
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
import { ingest } from '@kadena/docs-tools'; | ||
import type { IScriptResult } from './types'; | ||
import { initFunc } from './utils/build'; | ||
// eslint-disable-next-line @typescript-eslint/no-floating-promises | ||
(async function (): Promise<void> { | ||
async function ingestion(): Promise<IScriptResult> { | ||
const errors = []; | ||
const success = []; | ||
const namespace = 'docs_playground'; | ||
console.log(`\nINGESTING DATA TO "${namespace}" INDEX\n`); | ||
try { | ||
await ingest({ | ||
sourceIdentifiers: ['src/pages/**/*.md', 'src/specs/**/*.json'], | ||
source: 'fs', | ||
db: 'Algolia', | ||
isDryRun: false, | ||
ignore: [], | ||
namespace, | ||
}); | ||
success.push(`Ingestion successful for ${namespace} index`); | ||
} catch (e) { | ||
errors.push(e); | ||
errors.push(`Ingestion failed for ${namespace} index`); | ||
} | ||
return { | ||
errors, | ||
success, | ||
}; | ||
} | ||
|
||
await initFunc(ingestion, 'Ingesting data to Algolia'); | ||
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
72 changes: 72 additions & 0 deletions
72
packages/tools/docs-tools/src/ingestion/cli/client/algolia.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
import type { SearchClient } from 'algoliasearch'; | ||
import algoliasearch from 'algoliasearch'; | ||
import type { IMetaData } from '../../shared/index.js'; | ||
import { ALGOLIA_API_KEY, ALGOLIA_APP_ID, ALGOLIA_INDEX_NAME } from '../env.js'; | ||
import type { | ||
IQueryOptions, | ||
IUpsertVectorOptions, | ||
VectorDatabase, | ||
} from '../types.js'; | ||
|
||
interface IMetaDataHit extends IMetaData { | ||
metadata: Record<string, unknown>; | ||
} | ||
|
||
export class Algolia implements VectorDatabase { | ||
private _appId: string; | ||
private _apiKey: string; | ||
private _indexName: string; | ||
private _client?: SearchClient; | ||
|
||
public constructor() { | ||
if (!ALGOLIA_APP_ID) | ||
throw new Error('Missing ALGOLIA_APP_ID environment variable'); | ||
if (!ALGOLIA_API_KEY) | ||
throw new Error('Missing ALGOLIA_API_KEY environment variable'); | ||
if (!ALGOLIA_INDEX_NAME) | ||
throw new Error('Missing ALGOLIA_INDEX_NAME environment variable'); | ||
this._appId = ALGOLIA_APP_ID; | ||
this._apiKey = ALGOLIA_API_KEY; | ||
this._indexName = ALGOLIA_INDEX_NAME; | ||
} | ||
|
||
public setClient(): void { | ||
// @ts-ignore This expression is not callable, ts(2349) | ||
const client = algoliasearch(this._appId, this._apiKey); | ||
this._client = client; | ||
} | ||
|
||
public getClient(): SearchClient | undefined { | ||
if (!this._client) this.setClient(); | ||
return this._client; | ||
} | ||
|
||
public getIndex(): ReturnType<SearchClient['initIndex']> | undefined { | ||
const _client = this.getClient(); | ||
return _client?.initIndex(this._indexName); | ||
} | ||
|
||
public async upsertVectors({ | ||
vectors, | ||
}: IUpsertVectorOptions): Promise<number> { | ||
const index = this.getIndex(); | ||
if (!index) return 0; | ||
|
||
const objects = vectors.map((v) => ({ objectID: v.id, ...v.metadata })); | ||
const { objectIDs } = await index.saveObjects(objects); | ||
return objectIDs.length; | ||
} | ||
|
||
public async query({ embedding }: IQueryOptions): Promise<IMetaData[]> { | ||
const index = this.getIndex(); | ||
if (!index) return []; | ||
const { hits } = await index.search<IMetaDataHit>(embedding.join(',')); | ||
return hits.map((hit) => ({ | ||
filePath: hit.filePath, | ||
url: hit.url, | ||
content: hit.content, | ||
title: hit.title, | ||
...hit.metadata, | ||
})); | ||
} | ||
} |
127 changes: 127 additions & 0 deletions
127
packages/tools/docs-tools/src/ingestion/cli/command/ingest.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,127 @@ | ||
import * as fs from 'fs'; | ||
import path from 'node:path'; | ||
import type { IMetaData } from '../../shared/index.js'; | ||
import { CHUNK_SIZE } from '../../shared/index.js'; | ||
import { Algolia } from '../client/algolia.js'; | ||
import { fetchDocuments, sources } from '../fetcher/index.js'; | ||
import { parseDocument } from '../parser/index.js'; | ||
import { generateId } from '../util/crypto.js'; | ||
import ora from '../util/ora.js'; | ||
import { getInitUsage } from '../util/usage.js'; | ||
|
||
const targets = { | ||
Algolia, | ||
}; | ||
|
||
interface IOptions { | ||
source?: string; | ||
sourceIdentifiers: string[]; | ||
ignore: string[]; | ||
db?: string; | ||
namespace: string; | ||
isDryRun: boolean; | ||
} | ||
|
||
const isValidSource = (source?: string): source is keyof typeof sources => | ||
Boolean(source && source in sources); | ||
const isValidTarget = (target?: string): target is keyof typeof targets => | ||
Boolean(target && target in targets); | ||
|
||
export const ingest = async (options: IOptions): Promise<void> => { | ||
const { source, sourceIdentifiers, ignore, db, namespace, isDryRun } = | ||
options; | ||
|
||
if (!isValidSource(source)) throw new Error(`Invalid --source: ${source}`); | ||
if (!isValidTarget(db)) throw new Error(`Invalid --db: ${db}`); | ||
const spinner = ora(`Fetching files`).start(); | ||
|
||
const files = await fetchDocuments(source, sourceIdentifiers, { | ||
ignore, | ||
}); | ||
|
||
spinner.succeed(); | ||
|
||
if (files.length > 0) { | ||
const spinner = ora('Creating and upserting vector embeddings').start(); | ||
|
||
const DB = new targets[db](); | ||
|
||
const counters = { | ||
files: files.length, | ||
vectors: 0, | ||
usage: getInitUsage(), | ||
}; | ||
|
||
try { | ||
for (const file of files) { | ||
const { content, url, filePath } = file; | ||
|
||
if (!content) continue; | ||
|
||
spinner.text = `Creating and upserting vector embedding for: ${filePath}`; | ||
|
||
const { title, sections } = await parseDocument( | ||
filePath, | ||
content, | ||
CHUNK_SIZE, | ||
); | ||
|
||
console.log({ | ||
title, | ||
sections, | ||
}); | ||
|
||
if (isDryRun) continue; | ||
spinner.text = `Creating and upserting vector embedding for: ${filePath}`; | ||
|
||
const vectors = sections.map((section) => { | ||
// eslint-disable-next-line prefer-template | ||
const id = generateId(filePath + '\n' + section.content.trim()); | ||
// const id = generateId(`${filePath}'\n'${section.content.trim()}`); | ||
const metadata: IMetaData = { | ||
title: title || '', | ||
url, | ||
filePath, | ||
content: section.content, | ||
header: section.header, | ||
tags: section.tags, | ||
}; | ||
console.log('metadata: ', metadata); | ||
return { id, metadata }; | ||
}); | ||
|
||
console.log('vectors: ', vectors); | ||
const fileDest = path.join('./dump', '', `${filePath}.json`); | ||
const dirname = path.dirname(fileDest); | ||
if (!fs.existsSync(dirname)) { | ||
fs.mkdirSync(dirname, { recursive: true }); | ||
} | ||
|
||
fs.writeFileSync(fileDest, JSON.stringify(vectors), 'utf-8'); | ||
|
||
const insertedVectorCount = await DB.upsertVectors({ | ||
namespace, | ||
vectors, | ||
}); | ||
|
||
counters.vectors += insertedVectorCount; | ||
} | ||
|
||
spinner.succeed('Creating and upserting vectors'); | ||
} catch (error) { | ||
console.log(error); | ||
if (error instanceof Error) spinner.fail(error.message); | ||
else throw error; | ||
} finally { | ||
const messages = [ | ||
`Fetched ${counters.files} file(s) from ${source}`, | ||
`upserted ${counters.vectors} vectors to ${db}`, | ||
]; | ||
ora(messages.join(', ')).info(); | ||
} | ||
} else { | ||
throw new Error( | ||
`Unable to find files to ingest (source: ${source}, patterns: ${sourceIdentifiers.join(',')})`, | ||
); | ||
} | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
import * as dotenv from 'dotenv'; | ||
import { get } from './util/storage.js'; | ||
|
||
dotenv.config(); | ||
|
||
export const ALGOLIA_APP_ID = | ||
process.env.ALGOLIA_APP_ID ?? get('env', 'ALGOLIA_APP_ID'); | ||
export const ALGOLIA_API_KEY = | ||
process.env.ALGOLIA_API_KEY ?? get('env', 'ALGOLIA_API_KEY'); | ||
export const ALGOLIA_INDEX_NAME = | ||
process.env.ALGOLIA_INDEX_NAME ?? get('env', 'ALGOLIA_INDEX_NAME'); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
import fg from 'fast-glob'; | ||
import fs from 'node:fs/promises'; | ||
import type { FetchFiles } from '../types.js'; | ||
|
||
interface IFileData { | ||
filePath: string; | ||
url: string; | ||
content: Buffer; | ||
} | ||
|
||
const getFileData = async (filePath: string): Promise<IFileData> => { | ||
console.log('files: ', filePath); | ||
return { filePath, url: '', content: await fs.readFile(filePath) }; | ||
}; | ||
|
||
export const fetchFiles: FetchFiles = async (patterns, { ignore }) => { | ||
const files = await fg(patterns, { ignore }); | ||
return Promise.all(files.map(getFileData)); | ||
}; |
21 changes: 21 additions & 0 deletions
21
packages/tools/docs-tools/src/ingestion/cli/fetcher/http.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
import type { FetchFiles } from '../types.js'; | ||
|
||
export const fetchFiles: FetchFiles = async (urls) => { | ||
return Promise.all( | ||
urls.map(async (url) => { | ||
const _url = new URL(url); | ||
const response = await fetch(_url); | ||
|
||
if (!response.ok) | ||
console.error(`${response.status} ${response.statusText}: ${url}`); | ||
|
||
const filePath = _url.pathname.replace(/(\.html?)?$/, '.html'); | ||
|
||
return { | ||
filePath, | ||
url, | ||
content: Buffer.from(await response.arrayBuffer()), | ||
}; | ||
}), | ||
); | ||
}; |
16 changes: 16 additions & 0 deletions
16
packages/tools/docs-tools/src/ingestion/cli/fetcher/index.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
import type { IFile } from '../types.js'; | ||
import * as fs from './fs.js'; | ||
import * as http from './http.js'; | ||
|
||
export const sources = { | ||
fs, | ||
http, | ||
} as const; | ||
|
||
export const fetchDocuments = async ( | ||
source: keyof typeof sources, | ||
identifiers: string[], | ||
options: { ignore: string[] }, | ||
): Promise<IFile[]> => { | ||
return sources[source].fetchFiles(identifiers, options); | ||
}; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this is hardcoded for now to test it locally and play around. we need to change this to support as param/cli args for dev and prod support