Skip to content
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: expose flag to determine whether a composite is indexed #196

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion packages/cli/src/commands/composite/compile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export default class CompositeCompile extends Command<Flags> {
composite = await Composite.fromJSON({ ceramic: this.ceramic, definition })
outputPaths = allArgs
} else if (this.stdin === undefined && allArgs.length >= 2) {
composite = await readEncodedComposite(this.ceramic, allArgs[0])
composite = await readEncodedComposite(this.ceramic, allArgs[0], false)
outputPaths = allArgs.splice(1)
} else if (this.stdin !== undefined && allArgs.length < 1) {
this.spinner.fail(
Expand Down
14 changes: 13 additions & 1 deletion packages/cli/src/commands/composite/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { createComposite, writeEncodedComposite } from '@composedb/devtools-node

type Flags = CommandFlags & {
output?: string
deploy: boolean
}

export default class CreateComposite extends Command<Flags, { schemaFilePath: string }> {
Expand All @@ -23,12 +24,23 @@ export default class CreateComposite extends Command<Flags, { schemaFilePath: st
char: 'o',
description: 'path to the file where the composite representation should be saved',
}),
deploy: Flags.boolean({
char: 'd',
description:
'Deploy the composite to the ceramic node, which will start indexing on the composite',
default: true,
Copy link
Contributor

Choose a reason for hiding this comment

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

I don't feel super strongly about it, but I lean towards making create not deploy by default, so users have to explicitly deploy when they're ready. I think this will help with more complex situations where devs wants to create and merge multiple composites, possibly adding indices and views along the way, before finally deploying the final unified composite as the last step.

I could be swayed on this though if there's a case for why it's better to deploy by default

Copy link
Contributor

Choose a reason for hiding this comment

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

Also, what does composite:from-model do? That one seems even more like it definitely shouldn't auto-deploy since you're likely to want to add indices to it before deploying. And if that one doesn't auto-deploy, then I feel like this shouldn't either just for consistency sake if nothing else

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I was doing this just to maintain the existing behavior, so this change won't suddenly cause things to "stop working" for users that aren't calling deploy.

I'm not entirely sure which way is better either.

Copy link
Contributor

Choose a reason for hiding this comment

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

okay, I guess preserving existing behavior makes sense

allowNo: true,
}),
}

async run(): Promise<void> {
try {
this.spinner.start('Creating the composite...')
const composite = await createComposite(this.ceramic, this.args.schemaFilePath)
const composite = await createComposite(
this.ceramic,
this.args.schemaFilePath,
this.flags.deploy,
)
if (this.flags.output != null) {
const output = this.flags.output
await writeEncodedComposite(composite, output)
Expand Down
6 changes: 5 additions & 1 deletion packages/cli/src/commands/composite/deploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,11 @@ export default class CompositeDeploy extends Command<
let composite: Composite | undefined = undefined
if (this.stdin !== undefined) {
const definition = JSON.parse(this.stdin) as EncodedCompositeDefinition
composite = await Composite.fromJSON({ ceramic: this.ceramic, definition, index: true })
composite = await Composite.fromJSON({
ceramic: this.ceramic,
definition,
index: true,
})
} else if (this.args.compositePath !== undefined) {
composite = await readEncodedComposite(this.ceramic, this.args.compositePath, true)
} else {
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/commands/composite/extract-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export default class CompositeExtractModel extends Command<Flags> {
composite = await Composite.fromJSON({ ceramic: this.ceramic, definition })
modelsToExtract = allArgs
} else if (this.stdin === undefined && allArgs.length >= 2) {
composite = await readEncodedComposite(this.ceramic, allArgs[0])
composite = await readEncodedComposite(this.ceramic, allArgs[0], false)
modelsToExtract = allArgs.splice(1)
} else if (this.stdin !== undefined && allArgs.length < 1) {
this.spinner.fail(
Expand Down
8 changes: 8 additions & 0 deletions packages/cli/src/commands/composite/from-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { writeEncodedComposite } from '@composedb/devtools-node'

type Flags = CommandFlags & {
output?: string
deploy: boolean
}

export default class CompositeFromModel extends Command<Flags> {
Expand All @@ -18,6 +19,12 @@ export default class CompositeFromModel extends Command<Flags> {
char: 'o',
description: 'path to the file where the composite representation should be saved',
}),
deploy: Flags.boolean({
char: 'd',
description:
'Deploy the composite to the ceramic node, which will start indexing on the composite',
default: false,
}),
}

async run(): Promise<void> {
Expand All @@ -44,6 +51,7 @@ export default class CompositeFromModel extends Command<Flags> {
const composite = await Composite.fromModels({
ceramic: this.ceramic,
models: allModelStreamIDs,
index: this.flags.deploy,
})
if (this.flags.output != null) {
const output = this.flags.output
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/commands/composite/merge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export default class CompositeMerge extends Command<Flags> {
try {
this.spinner.start('Merging composites...')
const composites = await Promise.all(
compositePaths.map(async (path) => await readEncodedComposite(this.ceramic, path)),
compositePaths.map(async (path) => await readEncodedComposite(this.ceramic, path, false)),
)

const commonEmbedsFlag = this.flags['common-embeds'] as string | undefined
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/commands/composite/models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export default class CompositeModels extends Command<
const definition = JSON.parse(this.stdin) as EncodedCompositeDefinition
composite = await Composite.fromJSON({ ceramic: this.ceramic, definition })
} else if (this.args.compositePath !== undefined) {
composite = await readEncodedComposite(this.ceramic, this.args.compositePath)
composite = await readEncodedComposite(this.ceramic, this.args.compositePath, false)
} else {
this.spinner.fail(
'You need to pass a path to encoded composite either via an arg or through stdin',
Expand Down
43 changes: 36 additions & 7 deletions packages/cli/test/composites.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import fs from 'fs-extra'
import stripAnsi from 'strip-ansi'
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import { TEST_OUTPUT_DIR_PATH } from '../globalConsts.js' // not a module
import { TEST_OUTPUT_DIR_PATH } from '../globalConsts.js'
import { StreamID } from '@ceramicnetwork/streamid'

const { readFile, readJSON } = fs

Expand All @@ -18,6 +19,11 @@ const MODEL1_JSON =
const MODEL2_JSON =
'{"version": "1.0","name":"Model2","accountRelation":{"type":"list"},"schema":{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object","properties":{"stringPropName":{"type":"string","maxLength":80}},"additionalProperties":false,"required":["stringPropName"]}}'

async function checkIfModelIndexed(ceramic: CeramicClient, streamId: string): Promise<boolean> {
const models = await ceramic.admin.getIndexedModels()
return models.includes(StreamID.fromString(streamId))
}

describe('composites', () => {
const seed = '3a6de55a5ef33d110a5a37438704b0f0cb77ca5977131775a70ffd1c23779c8c'

Expand Down Expand Up @@ -56,17 +62,38 @@ describe('composites', () => {
).toBe(true)
}, 60000)

test('composite creation succeeds', async () => {
test('composite creation succeeds but model is not deployed', async () => {
const ceramic = new CeramicClient()
const create = await execa('bin/run.js', [
'composite:create',
'test/mocks/composite.profile.post.schema',
`--did-private-key=${seed}`,
`--no-deploy`,
])
const output = create.stdout.toString()
const def = JSON.parse(output) as EncodedCompositeDefinition
expect(def.version).toBe('1.1')
expect(Object.keys(def.version).length).not.toBe(0)
expect(def.aliases).toBeNull()
expect(def.views).toBeNull()
await expect(checkIfModelIndexed(ceramic, Object.keys(def.models)[0])).resolves.toBeFalsy()
dbcfd marked this conversation as resolved.
Show resolved Hide resolved
}, 60000)

test('composite creation succeeds and model is deployed', async () => {
const ceramic = new CeramicClient()
const create = await execa('bin/run.js', [
'composite:create',
'test/mocks/composite.profile.post.schema',
`--did-private-key=${seed}`,
'--deploy',
])
const output = create.stdout.toString()
expect(output.includes('"version":"1.1"')).toBe(true)
expect(output.includes('"indices":{"')).toBe(true)
expect(output.includes('"aliases":')).toBe(true)
expect(output.includes('"views":')).toBe(true)
const def = JSON.parse(output) as EncodedCompositeDefinition
expect(def.version).toBe('1.1')
expect(Object.keys(def.version).length).not.toBe(0)
expect(def.aliases).toBeNull()
expect(def.views).toBeNull()
await expect(checkIfModelIndexed(ceramic, Object.keys(def.models)[0])).resolves.toBeTruthy()
}, 60000)
})

Expand All @@ -91,6 +118,7 @@ describe('composites', () => {
return model
}),
])

return wasModelLoaded
}

Expand All @@ -105,7 +133,7 @@ describe('composites', () => {
).toBe(true)
}, 60000)

test('composite deployment succeeds', async () => {
test('composite deployment succeeds and is indexed by default', async () => {
const nonExistentModelStreamID = Object.keys(
(undeployedComposite as EncodedCompositeDefinition).models,
)[0]
Expand All @@ -125,6 +153,7 @@ describe('composites', () => {

const doesModelExistNow = await checkIfModelExist(ceramic, nonExistentModelStreamID)
expect(doesModelExistNow).toBeTruthy()
await expect(checkIfModelIndexed(ceramic, nonExistentModelStreamID)).resolves.toBeTruthy()
}, 60000)
})

Expand Down
16 changes: 10 additions & 6 deletions packages/devtools-node/src/fs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import { resolve } from 'path'
import { cwd } from 'process'
// // fs-extra is a CommonJS module
const { readFile, readJSON, writeFile, writeJSON, ensureDir } = fs

Check warning on line 9 in packages/devtools-node/src/fs.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test on Node 20 and macOS-latest

Caution: `fs` also has a named export `readFile`. Check if you meant to write `import {readFile} from 'fs-extra'` instead

Check warning on line 9 in packages/devtools-node/src/fs.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test on Node 20 and macOS-latest

Caution: `fs` also has a named export `readJSON`. Check if you meant to write `import {readJSON} from 'fs-extra'` instead

Check warning on line 9 in packages/devtools-node/src/fs.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test on Node 20 and macOS-latest

Caution: `fs` also has a named export `writeFile`. Check if you meant to write `import {writeFile} from 'fs-extra'` instead

Check warning on line 9 in packages/devtools-node/src/fs.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test on Node 20 and macOS-latest

Caution: `fs` also has a named export `writeJSON`. Check if you meant to write `import {writeJSON} from 'fs-extra'` instead

Check warning on line 9 in packages/devtools-node/src/fs.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test on Node 20 and macOS-latest

Caution: `fs` also has a named export `ensureDir`. Check if you meant to write `import {ensureDir} from 'fs-extra'` instead

Check warning on line 9 in packages/devtools-node/src/fs.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test on Node 20 and ubuntu-latest

Caution: `fs` also has a named export `readFile`. Check if you meant to write `import {readFile} from 'fs-extra'` instead

Check warning on line 9 in packages/devtools-node/src/fs.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test on Node 20 and ubuntu-latest

Caution: `fs` also has a named export `readJSON`. Check if you meant to write `import {readJSON} from 'fs-extra'` instead

Check warning on line 9 in packages/devtools-node/src/fs.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test on Node 20 and ubuntu-latest

Caution: `fs` also has a named export `writeFile`. Check if you meant to write `import {writeFile} from 'fs-extra'` instead

Check warning on line 9 in packages/devtools-node/src/fs.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test on Node 20 and ubuntu-latest

Caution: `fs` also has a named export `writeJSON`. Check if you meant to write `import {writeJSON} from 'fs-extra'` instead

Check warning on line 9 in packages/devtools-node/src/fs.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test on Node 20 and ubuntu-latest

Caution: `fs` also has a named export `ensureDir`. Check if you meant to write `import {ensureDir} from 'fs-extra'` instead
import * as pathModule from 'path'

import type { PathInput } from './types.js'
Expand All @@ -25,9 +25,13 @@
/**
* Create a Composite from a GraphQL schema path.
*/
export async function createComposite(ceramic: CeramicClient, path: PathInput): Promise<Composite> {
export async function createComposite(
ceramic: CeramicClient,
path: PathInput,
deploy: boolean,
Copy link
Contributor

Choose a reason for hiding this comment

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

That's a breaking API change, please set a default value or bump to v0.7 with docs updates.

): Promise<Composite> {
const file = await readFile(getFilePath(path))
return await Composite.create({ ceramic, schema: file.toString() })
return await Composite.create({ ceramic, schema: file.toString(), index: deploy })
}

/**
Expand All @@ -36,12 +40,12 @@
export async function readEncodedComposite(
ceramic: CeramicClient | string,
path: PathInput,
index?: boolean,
deploy?: boolean,
): Promise<Composite> {
const client = typeof ceramic === 'string' ? new CeramicClient(ceramic) : ceramic
const file = getFilePath(path)
const definition = (await readJSON(file)) as EncodedCompositeDefinition
return Composite.fromJSON({ ceramic: client, definition: definition, index: index })
return Composite.fromJSON({ ceramic: client, definition: definition, index: deploy })
}

/**
Expand Down Expand Up @@ -112,7 +116,7 @@
runtimePath: PathInput,
schemaPath?: PathInput,
): Promise<void> {
const definition = await readEncodedComposite(ceramic, definitionPath)
const definition = await readEncodedComposite(ceramic, definitionPath, false)
const runtime = definition.toRuntime()
await writeRuntimeDefinition(runtime, runtimePath)
if (schemaPath != null) {
Expand All @@ -130,7 +134,7 @@
): Promise<string> {
const sources = Array.isArray(source) ? source : [source]
const composites = await Promise.all(
sources.map(async (path) => await readEncodedComposite(ceramic, path)),
sources.map(async (path) => await readEncodedComposite(ceramic, path, false)),
)
const file = getFilePath(destination)
await writeEncodedComposite(Composite.from(composites), file)
Expand Down
2 changes: 1 addition & 1 deletion packages/devtools-node/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,6 @@ export async function serveEncodedDefinition(
params: ServeDefinitionParams,
): Promise<GraphQLServer> {
const { path, ...rest } = params
const composite = await readEncodedComposite(params.ceramicURL, path)
const composite = await readEncodedComposite(params.ceramicURL, path, false)
return await serveGraphQL({ ...rest, definition: composite.toRuntime() })
}
12 changes: 12 additions & 0 deletions website/docs/api/commands/cli.composite.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ Create an encoded composite definition from GraphQL [Composite Schema](https://d

You can find a detailed guide on the creation of Composites [here](https://developers.ceramic.network/docs/composedb/guides/data-modeling/composites)

If updating your composite by specifying additional fields to filter on using the `createIndex` directive, run this
command with `--no-deploy`. Your GraphQL definition will still be updated, but Ceramic will not attempt to re-index the
models in your composite. For other updates to your composite, such as adding new models, run with `--deploy`.

```
USAGE
$ composedb composite:create INPUT
Expand All @@ -57,6 +61,9 @@ OPTIONS
-c, --ceramic-url Ceramic API URL
-k, --did-private-key DID Private Key (you can generate a fresh private key using composedb did:generate-private-key)
-o, --output a path to file where the resulting encoded composite definition should be saved
-d, --deploy Deploy the composite to the ceramic node, which will cause the node to start indexing the
models contained within the composite
--no-deploy Do not deploy the composite to the ceramic node
```

### `composedb composite:models`
Expand Down Expand Up @@ -117,6 +124,10 @@ available on the Ceramic Node that yor DApp connects to. You can find a detailed
guide on Composites' deployment
[here](https://developers.ceramic.network/docs/composedb/guides/data-modeling/composites#deploying-composites)

If updating your composite by specifying additional fields to filter on using the `createIndex` directive, do not run
this command. Your GraphQL definition will still be updated, but Ceramic will not attempt to re-index the
models in your composite. For other updates to your composite, such as adding new models, run with `--deploy`.

```
USAGE
$ composedb composite:deploy PATH
Expand All @@ -126,6 +137,7 @@ ARGUMENTS

OPTIONS
-c, --ceramic-url Ceramic API URL
-k, --did-private-key DID Private Key (you can generate a fresh private key using composedb did:generate-private-key)
```

### `composedb composite:compile`
Expand Down
Loading