Skip to content

Commit

Permalink
fix flags, events
Browse files Browse the repository at this point in the history
  • Loading branch information
Roy Razon committed Nov 29, 2023
1 parent 4cb2495 commit 1c230d1
Show file tree
Hide file tree
Showing 18 changed files with 33 additions and 30 deletions.
11 changes: 9 additions & 2 deletions packages/cli-common/src/commands/base-command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,16 @@ import {
LogLevel, Logger, logLevels, ComposeModel, ProcessError, telemetryEmitter,
} from '@preevy/core'
import { asyncReduce } from 'iter-tools-es'
import { ParsingToken } from '@oclif/core/lib/interfaces/parser'
import { commandLogger } from '../lib/log'
import { composeFlags, pluginFlags } from '../lib/common-flags'

// eslint-disable-next-line no-use-before-define
export type Flags<T extends typeof Command> = Interfaces.InferredFlags<typeof BaseCommand['baseFlags'] & T['flags']>
export type Args<T extends typeof Command> = Interfaces.InferredArgs<T['args']>

const argsFromRaw = (raw: ParsingToken[]) => raw.filter(arg => arg.type === 'arg').map(arg => arg.input).filter(Boolean)

abstract class BaseCommand<T extends typeof Command=typeof Command> extends Command {
static baseFlags = {
'log-level': Flags.custom<LogLevel>({
Expand All @@ -35,6 +38,7 @@ abstract class BaseCommand<T extends typeof Command=typeof Command> extends Comm

protected flags!: Flags<T>
protected args!: Args<T>
#rawArgs!: ParsingToken[]

#userModel?: ComposeModel
protected async userModel() {
Expand Down Expand Up @@ -76,24 +80,27 @@ abstract class BaseCommand<T extends typeof Command=typeof Command> extends Comm

public async init(): Promise<void> {
await super.init()
const { args, flags } = await this.parse({
const { args, flags, raw } = await this.parse({
flags: this.ctor.flags,
baseFlags: super.ctor.baseFlags,
args: this.ctor.args,
strict: this.ctor.strict,
strict: false,
})
this.args = args as Args<T>
this.flags = flags as Flags<T>
if (this.flags.debug) {
oclifSettings.debug = true
}
this.#rawArgs = raw
this.logger = commandLogger(this, this.flags.json ? 'stderr' : 'stdout')
this.stdErrLogger = commandLogger(this, 'stderr')
}

protected logger!: Logger
protected stdErrLogger!: Logger

protected get rawArgs() { return argsFromRaw(this.#rawArgs) }

public get logLevel(): LogLevel {
return this.flags['log-level'] ?? this.flags.debug ? 'debug' : 'info'
}
Expand Down
2 changes: 1 addition & 1 deletion packages/cli-common/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ export { PluginContext, PluginInitContext } from './lib/plugins/context'
export {
composeFlags, pluginFlags, envIdFlags, tunnelServerFlags, urlFlags, buildFlags, tableFlags, parseBuildFlags,
} from './lib/common-flags'
export { formatFlagsToArgs, parseFlags, ParsedFlags, argsFromRaw } from './lib/flags'
export { formatFlagsToArgs, parseFlags, ParsedFlags } from './lib/flags'
export { initHook } from './hooks/init/load-plugins'
export { default as BaseCommand } from './commands/base-command'
3 changes: 0 additions & 3 deletions packages/cli-common/src/lib/flags.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { Flag } from '@oclif/core/lib/interfaces'
import { ParsingToken } from '@oclif/core/lib/interfaces/parser'
import { Parser } from '@oclif/core/lib/parser/parse'

type FlagSpec<T> =Pick<Flag<T>, 'type' | 'default'>
Expand Down Expand Up @@ -35,5 +34,3 @@ export const parseFlags = async <T extends {}>(def: T, argv: string[]) => (await
}).parse()).flags

export type ParsedFlags<T extends {}> = Omit<Awaited<ReturnType<typeof parseFlags<T>>>, 'json'>

export const argsFromRaw = (raw: ParsingToken[]) => raw.filter(arg => arg.type === 'arg').map(arg => arg.input).filter(Boolean)
2 changes: 1 addition & 1 deletion packages/cli/src/commands/down.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export default class Down extends DriverCommand<typeof Down> {

async run(): Promise<unknown> {
const log = this.logger
const { flags } = await this.parse(Down)
const { flags } = this
const driver = await this.driver()

const envId = await findEnvId({
Expand Down
4 changes: 1 addition & 3 deletions packages/cli/src/commands/logs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import {
localComposeClient, findEnvId, MachineConnection, ComposeModel, remoteUserModel, dockerEnvContext,
} from '@preevy/core'
import { COMPOSE_TUNNEL_AGENT_SERVICE_NAME } from '@preevy/common'
import { argsFromRaw } from '@preevy/cli-common'
import DriverCommand from '../driver-command'
import { envIdFlags } from '../common-flags'

Expand Down Expand Up @@ -80,8 +79,7 @@ export default class Logs extends DriverCommand<typeof Logs> {

async run(): Promise<void> {
const log = this.logger
const { flags, raw } = await this.parse(Logs)
const restArgs = argsFromRaw(raw)
const { flags, rawArgs: restArgs } = this

let connection: MachineConnection
let userModel: ComposeModel
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/commands/ls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export default class Ls extends DriverCommand<typeof Ls> {
static enableJsonFlag = true

async run(): Promise<unknown> {
const { flags } = await this.parse(Ls)
const { flags } = this
const driver = await this.driver()
const machines = await asyncToArray(
asyncMap(
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/commands/proxy/disconnect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export default class Disconnect extends ProfileCommand<typeof Disconnect> {

// eslint-disable-next-line class-methods-use-this
async run(): Promise<unknown> {
const { args } = await this.parse(Disconnect)
const { args } = this
const inspector = commands.proxy.inspectRunningComposeApp(args['compose-project'])
const agentContainer = await inspector.getPreevyAgentContainer()
if (agentContainer) {
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/commands/purge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export default class Purge extends DriverCommand<typeof Purge> {
static strict = false

async run(): Promise<unknown> {
const { flags } = await this.parse(Purge)
const { flags } = this

const driver = await this.driver()
const resourcePlurals: Record<string, string> = { [machineResourceType]: 'machines', ...driver.resourcePlurals }
Expand Down
5 changes: 1 addition & 4 deletions packages/cli/src/commands/shell.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { Args } from '@oclif/core'
import { commands } from '@preevy/core'
import { argsFromRaw } from '@preevy/cli-common'
import DriverCommand from '../driver-command'

// eslint-disable-next-line no-use-before-define
Expand All @@ -21,11 +20,9 @@ export default class Shell extends DriverCommand<typeof Shell> {
static enableJsonFlag = false

async run(): Promise<unknown> {
const { args, raw } = await this.parse(Shell)
const { args, rawArgs: restArgs } = this
const driver = await this.driver()

const restArgs = argsFromRaw(raw).slice(1)

const result = await commands.shell({
envId: args.envId,
args: restArgs,
Expand Down
5 changes: 2 additions & 3 deletions packages/cli/src/commands/up.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
telemetryEmitter,
withSpinner,
} from '@preevy/core'
import { argsFromRaw, buildFlags, parseBuildFlags, tableFlags, text, tunnelServerFlags } from '@preevy/cli-common'
import { buildFlags, parseBuildFlags, tableFlags, text, tunnelServerFlags } from '@preevy/cli-common'
import { inspect } from 'util'
import { editUrl, tunnelNameResolver } from '@preevy/common'
import MachineCreationDriverCommand from '../machine-creation-driver-command'
Expand Down Expand Up @@ -111,8 +111,7 @@ export default class Up extends MachineCreationDriverCommand<typeof Up> {
}

async run(): Promise<unknown> {
const { flags, raw } = await this.parse(Up)
const restArgs = argsFromRaw(raw)
const { flags, rawArgs: restArgs } = this

const driver = await this.driver()
const machineCreationDriver = await this.machineCreationDriver()
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/commands/urls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ export default class Urls extends ProfileCommand<typeof Urls> {

async run(): Promise<unknown> {
const log = this.logger
const { flags, args } = await this.parse(Urls)
const { flags, args } = this

const envId = await findEnvId({
userSpecifiedEnvId: flags.id,
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/commands/version.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export default class Version extends BaseCommand<typeof Version> {
static enableJsonFlag = true

async run(): Promise<unknown> {
const { flags } = await this.parse(Version)
const { flags } = this
const log = this.logger

if (flags.json) {
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/hooks/init/telemetry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const hook: Hook.Init = async ({ config }) => {
return
}

const emitter = await createTelemetryEmitter(config)
const emitter = await createTelemetryEmitter({ ...config, filename: config.scopedEnvVar('TELEMETRY_FILE') })
registerEmitter(emitter)
wireProcessExit(process, emitter)
}
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/commands/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ const buildCommand = async ({
elapsed_sec: elapsedTimeSec,
has_registry: Boolean(buildSpec.registry),
})
log.info(`Elapsed time for build step: ${elapsedTimeSec.toLocaleString(undefined, { maximumFractionDigits: 2 })} sec`)
log.info(`Build step done in ${elapsedTimeSec.toLocaleString(undefined, { maximumFractionDigits: 2 })}s`)

return { buildModel, deployModel }
}
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/commands/up.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,12 +147,12 @@ const up = async ({
await using dockerContext = await dockerEnvContext({ connection, log })

const { elapsedTimeSec } = await measureTime(() => compose.spawnPromise(composeArgs, { stdio: 'inherit', env: dockerContext.env }))
telemetryEmitter().capture('provisioning success', {
telemetryEmitter().capture('provision success', {
elapsed_sec: elapsedTimeSec,
with_build: Boolean(buildSpec),
has_registry: Boolean(buildSpec?.registry),
})
log.info(`Elapsed time for provisioning step: ${elapsedTimeSec.toLocaleString(undefined, { maximumFractionDigits: 2 })} sec`)
log.info(`Provision step done in ${elapsedTimeSec.toLocaleString(undefined, { maximumFractionDigits: 2 })}s`)

return { composeModel, projectLocalDataDir }
}
Expand Down
9 changes: 7 additions & 2 deletions packages/core/src/telemetry/emitter.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import os from 'os'
import fs from 'fs'
import crypto from 'crypto'
import stringify from 'fast-safe-stringify'
import fetch from 'node-fetch'
Expand All @@ -20,23 +21,27 @@ type IdentifyFunction = {
(id: string, person?: TelemetryProperties): void
}

export const telemetryEmitter = async ({ dataDir, version, debug }: {
export const telemetryEmitter = async ({ dataDir, version, debug, filename }: {
dataDir: string
version: string
debug: number
filename?: string
}) => {
const machineId = await memoizedMachineId(dataDir)
let distinctId = machineId
const groupIdentities = {} as Record<GroupIdentityType, string>
const pendingEvents: TelemetryEvent[] = []
const runId = newRunId()
const file = filename ? fs.createWriteStream(filename, 'utf-8') : undefined // await fs.promises.open(filename, 'a') : undefined
let debounceDisabled = false
const flushLimit = pLimit(1)
const flush = async () => await flushLimit(async () => {
if (!pendingEvents.length) {
return
}
const body = stringify({ batch: pendingEvents.map(serializableEvent) })
const batch = pendingEvents.map(serializableEvent)
const body = stringify({ batch })
file?.write(batch.map(event => `${stringify(event)}${os.EOL}`).join(''))
pendingEvents.length = 0
const response = await fetch(TELEMETRY_URL, {
headers: { 'Content-Type': 'application/json' },
Expand Down
2 changes: 1 addition & 1 deletion packages/plugin-github/src/commands/github/pr/comment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ class CommentGithubPr extends BaseGithubPrCommand<typeof CommentGithubPr> {
'--json',
]) as FlatTunnel[]

const { flags } = await this.parse(CommentGithubPr)
const { flags } = this
const config = await this.loadGithubPullRequestCommentConfig(flags)

await upsertPreevyComment({
Expand Down
2 changes: 1 addition & 1 deletion packages/plugin-github/src/commands/github/pr/uncomment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class UnCommentGithubPr extends BaseGithubPrCommand<typeof UnCommentGithubPr> {
}

async run() {
const { flags } = await this.parse(UnCommentGithubPr)
const { flags } = this
const config = await this.loadGithubPullRequestCommentConfig(flags)

await upsertPreevyComment({
Expand Down

0 comments on commit 1c230d1

Please sign in to comment.