diff --git a/packages/blockstore-filestore/CHANGELOG.md b/packages/blockstore-filestore/CHANGELOG.md new file mode 100644 index 00000000..e69de29b diff --git a/packages/blockstore-filestore/LICENSE b/packages/blockstore-filestore/LICENSE new file mode 100644 index 00000000..20ce483c --- /dev/null +++ b/packages/blockstore-filestore/LICENSE @@ -0,0 +1,4 @@ +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 diff --git a/packages/blockstore-filestore/LICENSE-APACHE b/packages/blockstore-filestore/LICENSE-APACHE new file mode 100644 index 00000000..14478a3b --- /dev/null +++ b/packages/blockstore-filestore/LICENSE-APACHE @@ -0,0 +1,5 @@ +Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. diff --git a/packages/blockstore-filestore/LICENSE-MIT b/packages/blockstore-filestore/LICENSE-MIT new file mode 100644 index 00000000..72dc60d8 --- /dev/null +++ b/packages/blockstore-filestore/LICENSE-MIT @@ -0,0 +1,19 @@ +The MIT License (MIT) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/packages/blockstore-filestore/README.md b/packages/blockstore-filestore/README.md new file mode 100644 index 00000000..860ccb4d --- /dev/null +++ b/packages/blockstore-filestore/README.md @@ -0,0 +1,51 @@ +# blockstore-fs + +[![ipfs.tech](https://img.shields.io/badge/project-IPFS-blue.svg?style=flat-square)](https://ipfs.tech) +[![Discuss](https://img.shields.io/discourse/https/discuss.ipfs.tech/posts.svg?style=flat-square)](https://discuss.ipfs.tech) +[![codecov](https://img.shields.io/codecov/c/github/ipfs/js-stores.svg?style=flat-square)](https://codecov.io/gh/ipfs/js-stores) +[![CI](https://img.shields.io/github/actions/workflow/status/ipfs/js-stores/js-test-and-release.yml?branch=main\&style=flat-square)](https://github.com/ipfs/js-stores/actions/workflows/js-test-and-release.yml?query=branch%3Amain) + +> Blockstore implementation with file system backend + +## Table of contents + +- [Install](#install) +- [Usage](#usage) +- [API Docs](#api-docs) +- [License](#license) +- [Contribute](#contribute) + +## Install + +```console +$ npm i blockstore-filestore +``` + +## Usage + +```js +import { Filestore } from 'blockstore-filestore' + +const store = new Filestore(blockstore, datastore) +``` + +## API Docs + +## License + +Licensed under either of + +- Apache 2.0, ([LICENSE-APACHE](LICENSE-APACHE) / ) +- MIT ([LICENSE-MIT](LICENSE-MIT) / ) + +## Contribute + +Contributions welcome! Please check out [the issues](https://github.com/ipfs/js-stores/issues). + +Also see our [contributing document](https://github.com/ipfs/community/blob/master/CONTRIBUTING_JS.md) for more information on how we work, and about contributing in general. + +Please be aware that all interactions related to this repo are subject to the IPFS [Code of Conduct](https://github.com/ipfs/community/blob/master/code-of-conduct.md). + +Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. + +[![](https://cdn.rawgit.com/jbenet/contribute-ipfs-gif/master/img/contribute.gif)](https://github.com/ipfs/community/blob/master/CONTRIBUTING.md) diff --git a/packages/blockstore-filestore/package.json b/packages/blockstore-filestore/package.json new file mode 100644 index 00000000..d9097842 --- /dev/null +++ b/packages/blockstore-filestore/package.json @@ -0,0 +1,177 @@ +{ + "name": "blockstore-filestore", + "version": "0.1.0", + "description": "Blockstore implementation with no-copy file system backend", + "license": "Apache-2.0 OR MIT", + "homepage": "https://github.com/ipfs/js-stores/tree/master/packages/blockstore-filestore#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/ipfs/js-stores.git" + }, + "bugs": { + "url": "https://github.com/ipfs/js-stores/issues" + }, + "keywords": [ + "filestore", + "datastore", + "fs", + "interface", + "ipfs", + "key-value" + ], + "engines": { + "node": ">=16.0.0", + "npm": ">=7.0.0" + }, + "type": "module", + "types": "./dist/src/index.d.ts", + "typesVersions": { + "*": { + "*": [ + "*", + "dist/*", + "dist/src/*", + "dist/src/*/index" + ], + "src/*": [ + "*", + "dist/*", + "dist/src/*", + "dist/src/*/index" + ] + } + }, + "files": [ + "src", + "dist", + "!dist/test", + "!**/*.tsbuildinfo" + ], + "exports": { + ".": { + "types": "./dist/src/index.d.ts", + "import": "./dist/src/index.js" + } + }, + "eslintConfig": { + "extends": "ipfs", + "parserOptions": { + "sourceType": "module", + "project": [ + "tsconfig.json", + "benchmarks/encoding/tsconfig.json" + ] + } + }, + "release": { + "branches": [ + "main" + ], + "plugins": [ + [ + "@semantic-release/commit-analyzer", + { + "preset": "conventionalcommits", + "releaseRules": [ + { + "breaking": true, + "release": "major" + }, + { + "revert": true, + "release": "patch" + }, + { + "type": "feat", + "release": "minor" + }, + { + "type": "fix", + "release": "patch" + }, + { + "type": "docs", + "release": "patch" + }, + { + "type": "test", + "release": "patch" + }, + { + "type": "deps", + "release": "patch" + }, + { + "scope": "no-release", + "release": false + } + ] + } + ], + [ + "@semantic-release/release-notes-generator", + { + "preset": "conventionalcommits", + "presetConfig": { + "types": [ + { + "type": "feat", + "section": "Features" + }, + { + "type": "fix", + "section": "Bug Fixes" + }, + { + "type": "chore", + "section": "Trivial Changes" + }, + { + "type": "docs", + "section": "Documentation" + }, + { + "type": "deps", + "section": "Dependencies" + }, + { + "type": "test", + "section": "Tests" + } + ] + } + } + ], + "@semantic-release/changelog", + "@semantic-release/npm", + "@semantic-release/github", + "@semantic-release/git" + ] + }, + "scripts": { + "clean": "aegir clean", + "lint": "aegir lint", + "build": "aegir build --bundle false", + "generate": "protons ./src/pb/dataobj.proto", + "release": "aegir release", + "test": "aegir test -t node -t electron-main", + "test:node": "aegir test -t node", + "test:electron-main": "aegir test -t electron-main", + "dep-check": "aegir dep-check", + "docs": "aegir docs" + }, + "dependencies": { + "interface-datastore": "^8.2.3", + "multiformats": "^12.0.1", + "protons-runtime": "^5.0.0" + }, + "devDependencies": { + "aegir": "^39.0.9", + "interface-blockstore": "^5.2.3", + "interface-store": "^5.1.2", + "protons": "^7.0.2" + }, + "typedoc": { + "entryPoint": "./src/index.ts" + } +} diff --git a/packages/blockstore-filestore/src/index.ts b/packages/blockstore-filestore/src/index.ts new file mode 100644 index 00000000..8b544c73 --- /dev/null +++ b/packages/blockstore-filestore/src/index.ts @@ -0,0 +1,116 @@ +import { CID } from 'multiformats/cid' +import * as raw from 'multiformats/codecs/raw' +import { sha256 } from 'multiformats/hashes/sha2' +import { DataObj } from './pb/dataobj.js' +import { readChunk, cidToKey, keyToCid } from './utils.js' +import type { Blockstore, Pair } from 'interface-blockstore' +import type { Datastore } from 'interface-datastore' +import type { AbortOptions, AwaitIterable, Await } from 'interface-store' + +export class Filestore implements Blockstore { + private readonly blockstore: Blockstore + private readonly datastore: Datastore + + constructor (blockstore: Blockstore, datastore: Datastore) { + this.blockstore = blockstore + this.datastore = datastore + } + + async get (key: CID, options?: AbortOptions): Promise { + if (await this.blockstore.has(key, options)) { + const block = await this.blockstore.get(key, options) + + return block + } + + const dKey = cidToKey(key) + const index = await this.datastore.get(dKey, options) + const dataObj = DataObj.decode(index) + const chunk = await readChunk(dataObj.FilePath, dataObj.Offset, dataObj.Size) + const hash = await sha256.digest(chunk) + const cid = CID.create(key.version, raw.code, hash) + + if (!cid.equals(key)) { + throw new Error('CID does not match.') + } + + return chunk + } + + async * getMany (source: AwaitIterable, options?: AbortOptions): AsyncGenerator { + for await (const cid of source) { + const block = await this.get(cid, options) + + yield { cid, block } + } + } + + async * getAll (options?: AbortOptions): AsyncGenerator { + yield * this.blockstore.getAll(options) + + const keys = this.datastore.queryKeys({ filters: [() => true] }, options) + + for await (const key of keys) { + let cid: CID + + try { + cid = keyToCid(key) + } catch (error) { + continue + } + + const block = await this.get(cid, options) + + yield { block, cid } + } + } + + async has (key: CID): Promise { + if (await this.blockstore.has(key)) { + return true + } + + const dKey = cidToKey(key) + const hasKey = await this.datastore.has(dKey) + + return hasKey + } + + put (key: CID, val: Uint8Array, options?: AbortOptions): Await { + return this.blockstore.put(key, val, options) + } + + putMany (source: AwaitIterable, options?: AbortOptions): AwaitIterable { + return this.blockstore.putMany(source, options) + } + + async delete (key: CID, options?: AbortOptions): Promise { + const dKey = cidToKey(key) + + await Promise.all([ + this.blockstore.delete(key, options), + this.datastore.delete(dKey, options) + ]) + } + + async * deleteMany (source: AwaitIterable, options?: AbortOptions): AwaitIterable { + for await (const cid of source) { + await this.delete(cid, options) + yield cid + } + } + + async putLink (key: CID, path: string, offset: bigint, size: bigint, options?: AbortOptions): Promise { + const data = DataObj.encode({ + FilePath: path, + Offset: offset, + Size: size + }) + + const dKey = cidToKey(key) + + await this.datastore.put(dKey, data, options) + + return key + } +} diff --git a/packages/blockstore-filestore/src/pb/dataobj.proto b/packages/blockstore-filestore/src/pb/dataobj.proto new file mode 100644 index 00000000..d60990a8 --- /dev/null +++ b/packages/blockstore-filestore/src/pb/dataobj.proto @@ -0,0 +1,7 @@ +syntax = "proto3"; + +message DataObj { + string FilePath = 1; + uint64 Offset = 2; + uint64 Size = 3; +} diff --git a/packages/blockstore-filestore/src/pb/dataobj.ts b/packages/blockstore-filestore/src/pb/dataobj.ts new file mode 100644 index 00000000..a540b21b --- /dev/null +++ b/packages/blockstore-filestore/src/pb/dataobj.ts @@ -0,0 +1,87 @@ +/* eslint-disable import/export */ +/* eslint-disable complexity */ +/* eslint-disable @typescript-eslint/no-namespace */ +/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */ +/* eslint-disable @typescript-eslint/no-empty-interface */ + +import { encodeMessage, decodeMessage, message } from 'protons-runtime' +import type { Codec } from 'protons-runtime' +import type { Uint8ArrayList } from 'uint8arraylist' + +export interface DataObj { + FilePath: string + Offset: bigint + Size: bigint +} + +export namespace DataObj { + let _codec: Codec + + export const codec = (): Codec => { + if (_codec == null) { + _codec = message((obj, w, opts = {}) => { + if (opts.lengthDelimited !== false) { + w.fork() + } + + if ((obj.FilePath != null && obj.FilePath !== '')) { + w.uint32(10) + w.string(obj.FilePath) + } + + if ((obj.Offset != null && obj.Offset !== 0n)) { + w.uint32(16) + w.uint64(obj.Offset) + } + + if ((obj.Size != null && obj.Size !== 0n)) { + w.uint32(24) + w.uint64(obj.Size) + } + + if (opts.lengthDelimited !== false) { + w.ldelim() + } + }, (reader, length) => { + const obj: any = { + FilePath: '', + Offset: 0n, + Size: 0n + } + + const end = length == null ? reader.len : reader.pos + length + + while (reader.pos < end) { + const tag = reader.uint32() + + switch (tag >>> 3) { + case 1: + obj.FilePath = reader.string() + break + case 2: + obj.Offset = reader.uint64() + break + case 3: + obj.Size = reader.uint64() + break + default: + reader.skipType(tag & 7) + break + } + } + + return obj + }) + } + + return _codec + } + + export const encode = (obj: Partial): Uint8Array => { + return encodeMessage(obj, DataObj.codec()) + } + + export const decode = (buf: Uint8Array | Uint8ArrayList): DataObj => { + return decodeMessage(buf, DataObj.codec()) + } +} diff --git a/packages/blockstore-filestore/src/utils.ts b/packages/blockstore-filestore/src/utils.ts new file mode 100644 index 00000000..c5ff75be --- /dev/null +++ b/packages/blockstore-filestore/src/utils.ts @@ -0,0 +1,52 @@ +import fs from 'node:fs' +import { Key } from 'interface-datastore' +import { base32 } from 'multiformats/bases/base32' +import { CID } from 'multiformats/cid' +import * as raw from 'multiformats/codecs/raw' +import * as Digest from 'multiformats/hashes/digest' + +export const cidToKey = (cid: CID): Key => { + return new Key(`/${base32.encode(cid.multihash.bytes).slice(1).toUpperCase()}`, false) +} + +export const keyToCid = (key: Key): CID => { + return CID.createV1(raw.code, Digest.decode(base32.decode(`b${key.toString().slice(1).toLowerCase()}`))) +} + +export const readChunk = async (path: string, offset: bigint, size: bigint): Promise => { + const fd = await new Promise((resolve, reject) => { + fs.open(path, (err, fd) => { + if (err != null) { + reject(err) + } else { + resolve(fd) + } + }) + }) + + const data = await new Promise((resolve, reject) => { + fs.read(fd, { + position: offset, + length: Number(size), + buffer: Buffer.alloc(Number(size)) + }, (err, _, data: Uint8Array) => { + if (err != null) { + reject(err) + } else { + resolve(data) + } + }) + }) + + await new Promise((resolve, reject) => { + fs.close(fd, (err) => { + if (err != null) { + reject(err) + } else { + resolve() + } + }) + }) + + return data +} diff --git a/packages/blockstore-filestore/tsconfig.json b/packages/blockstore-filestore/tsconfig.json new file mode 100644 index 00000000..e27c7fa6 --- /dev/null +++ b/packages/blockstore-filestore/tsconfig.json @@ -0,0 +1,24 @@ +{ + "extends": "aegir/src/config/tsconfig.aegir.json", + "compilerOptions": { + "outDir": "dist" + }, + "include": [ + "src", + "test" + ], + "references": [ + { + "path": "../blockstore-core" + }, + { + "path": "../interface-blockstore" + }, + { + "path": "../interface-blockstore-tests" + }, + { + "path": "../interface-store" + } + ] +}