Skip to content

Commit

Permalink
fix: make context source required, add test helper for context data
Browse files Browse the repository at this point in the history
  • Loading branch information
ssube committed Apr 17, 2021
1 parent b8ad5e2 commit 88b0c85
Show file tree
Hide file tree
Showing 33 changed files with 182 additions and 187 deletions.
9 changes: 8 additions & 1 deletion src/BaseService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { SchemaError } from './error/SchemaError';
import { serviceLogger } from './logger';
import { ServiceModule } from './module/ServiceModule';
import { Schema } from './schema';
import { Service, ServiceDefinition, ServiceEvent } from './Service';
import { Service, ServiceDefinition, ServiceEvent, ServiceMetadata } from './Service';
import { Clock } from './utils/Clock';
import { JsonPath } from './utils/JsonPath';
import { MathFactory } from './utils/Math';
Expand Down Expand Up @@ -95,4 +95,11 @@ export abstract class BaseService<TData extends BaseServiceData> implements Serv
return this.id;
}
}

public getMetadata(): ServiceMetadata {
return {
kind: this.kind,
name: this.name,
};
}
}
3 changes: 2 additions & 1 deletion src/endpoint/BaseEndpoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,8 @@ export abstract class BaseEndpoint<TData extends EndpointData> extends BotServic
protected async createContext(options: ContextOptions): Promise<Context> {
const ctx = await this.contextRepository.save(new Context({
...options,
// TODO: does this need source/target?
source: this.getMetadata(),
// TODO: does this need target?
}));
this.logger.debug({ ctx }, 'endpoint saved new context');
return ctx;
Expand Down
4 changes: 4 additions & 0 deletions src/endpoint/GithubEndpoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ export class GithubEndpoint extends HookEndpoint<GithubEndpointData> {
id: data.repository.full_name,
thread: data.check_run.head_sha,
},
source: this.getMetadata(),
sourceUser: {
name: data.sender.login,
uid: this.data.hookUser,
Expand All @@ -100,6 +101,7 @@ export class GithubEndpoint extends HookEndpoint<GithubEndpointData> {
id: data.repository.full_name,
thread: data.check_suite.head_sha,
},
source: this.getMetadata(),
sourceUser: {
name: data.sender.login,
uid: this.data.hookUser,
Expand All @@ -119,6 +121,7 @@ export class GithubEndpoint extends HookEndpoint<GithubEndpointData> {
id: data.repository.full_name,
thread: data.pull_request.number,
},
source: this.getMetadata(),
sourceUser: {
name: data.sender.login,
uid: this.data.hookUser,
Expand All @@ -138,6 +141,7 @@ export class GithubEndpoint extends HookEndpoint<GithubEndpointData> {
id: data.repository.full_name,
thread: data.sha,
},
source: this.getMetadata(),
sourceUser: {
name: data.sender.login,
uid: this.data.hookUser,
Expand Down
11 changes: 11 additions & 0 deletions src/endpoint/GitlabEndpoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,10 @@ export class GitlabEndpoint extends HookEndpoint<GitlabEndpointData> implements
id: data.project_name,
thread: data.ref,
},
source: {
kind: this.kind,
name: this.name,
},
sourceUser: {
name: user.name,
uid: this.data.hookUser,
Expand All @@ -183,6 +187,10 @@ export class GitlabEndpoint extends HookEndpoint<GitlabEndpointData> implements
id: data.project.id,
thread: data.object_attributes.id,
},
source: {
kind: this.kind,
name: this.name,
},
sourceUser: {
name: user.name,
uid: this.data.hookUser,
Expand All @@ -204,6 +212,7 @@ export class GitlabEndpoint extends HookEndpoint<GitlabEndpointData> implements
id: data.project.id,
thread: data.object_attributes.id,
},
source: this.getMetadata(),
sourceUser: {
name: user.name,
uid: this.data.hookUser,
Expand All @@ -223,6 +232,7 @@ export class GitlabEndpoint extends HookEndpoint<GitlabEndpointData> implements
id: data.project.web_url,
thread: data.object_attributes.ref,
},
source: this.getMetadata(),
sourceUser: {
name: data.user.name,
uid: data.user.username,
Expand All @@ -242,6 +252,7 @@ export class GitlabEndpoint extends HookEndpoint<GitlabEndpointData> implements
id: data.project.web_url,
thread: data.ref,
},
source: this.getMetadata(),
sourceUser: {
name: data.user_name,
uid: data.user_username,
Expand Down
1 change: 1 addition & 0 deletions src/endpoint/HookEndpoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export class HookEndpoint<TData extends HookEndpointData> extends BaseEndpoint<T
const user = mustExist(this.hookUser);
return this.createContext({
channel,
source: this.getMetadata(),
sourceUser: {
name: user.name,
uid: this.data.hookUser,
Expand Down
31 changes: 16 additions & 15 deletions src/entity/Context.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { doesExist, isNil, NotFoundError } from '@apextoaster/js-utils';
import { doesExist, NotFoundError } from '@apextoaster/js-utils';
import { GraphQLInputObjectType, GraphQLObjectType, GraphQLString } from 'graphql';
import { flatten } from 'lodash';
import { flatten, isString } from 'lodash';
import { MissingValueError } from 'noicejs';
import { newTrie, ShiroTrie } from 'shiro-trie';
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
Expand Down Expand Up @@ -36,9 +36,9 @@ export interface ContextUser {

export interface ContextData {
channel: ContextChannel;
source?: ServiceMetadata;
source: ServiceMetadata;
sourceUser: ContextUser;
target?: ServiceMetadata;
target?: ServiceMetadata; // TODO: used at all?
}

export interface ContextOptions extends BaseEntityOptions, ContextData {
Expand Down Expand Up @@ -75,25 +75,25 @@ export class Context extends BaseEntity implements ContextOptions {

public parser?: Parser;

public source?: ServiceMetadata;
public source: ServiceMetadata;

public sourceUser: ContextUser;

public target?: ServiceMetadata;

public token?: Token;

public user?: User;

public sourceUser: ContextUser;

constructor(options: ContextOptions) {
super(options);

if (doesExist(options)) {
if (isNil(options.sourceUser.name)) {
if (isString(options.sourceUser.name) === false || options.sourceUser.name === '') {
throw new MissingValueError('name must be specified in context options');
}

if (isNil(options.sourceUser.uid)) {
if (isString(options.sourceUser.uid) === false || options.sourceUser.uid === '') {
throw new MissingValueError('uid must be specified in context options');
}

Expand All @@ -102,22 +102,23 @@ export class Context extends BaseEntity implements ContextOptions {
thread: options.channel.thread,
};
this.parser = options.parser;
this.token = options.token;
this.user = options.user;

// TODO: these should be taken from options.user or removed entirely
this.source = options.source;
this.sourceUser = {
...options.sourceUser,
};

// TODO: what are these for? entity should not link services
this.source = options.source;
this.target = options.target;
this.token = options.token;
this.user = options.user;
} else {
this.channel = {
id: '',
thread: '',
};
this.source = {
kind: '',
name: '',
};
this.sourceUser = {
name: '',
uid: '',
Expand Down
4 changes: 2 additions & 2 deletions src/listener/BaseListener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ export abstract class BaseListener<TData extends ListenerData> extends BotServic
protected async createContext(options: ContextOptions): Promise<Context> {
const ctx = await this.contextRepository.save(new Context({
...options,
source: this,
target: this,
source: this.getMetadata(),
target: this.getMetadata(),
}));
this.logger.debug({ ctx }, 'listener saved new context');
return ctx;
Expand Down
1 change: 1 addition & 0 deletions src/listener/DiscordListener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,7 @@ export class DiscordListener extends SessionListener<DiscordListenerData> implem
id: msg.channel.id,
thread: msg.id,
},
source: this.getMetadata(),
sourceUser: {
name: msg.author.username,
uid: msg.author.id,
Expand Down
1 change: 1 addition & 0 deletions src/listener/ExpressListener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ export class ExpressListener extends SessionListener<ExpressListenerData> implem
id: '',
thread: '',
},
source: this.getMetadata(),
sourceUser: {
name: token.user.name,
uid,
Expand Down
1 change: 1 addition & 0 deletions src/listener/GithubListener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ export class GithubListener extends SessionListener<GithubListenerData> {
id: `${repo.owner}/${repo.repo}`,
thread,
},
source: this.getMetadata(),
sourceUser: {
name: msg.user.login,
uid,
Expand Down
1 change: 1 addition & 0 deletions src/listener/SlackListener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,7 @@ export class SlackListener extends SessionListener<SlackListenerData> implements
id: channel,
thread: ts,
},
source: this.getMetadata(),
sourceUser: {
name: uid,
uid,
Expand Down
1 change: 1 addition & 0 deletions src/parser/BaseParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ export abstract class BaseParser<TData extends ParserData> extends BotService<TD
return this.contextRepository.save(new Context({
...baseContext,
parser: this,
source: this.getMetadata(),
}));
}

Expand Down
14 changes: 12 additions & 2 deletions src/utils/ContextRedirect.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,20 @@
import { defaultWhen, mustCoalesce } from '@apextoaster/js-utils';
import { defaultWhen, doesExist, mustCoalesce, Optional } from '@apextoaster/js-utils';

import { Context, ContextRedirect } from '../entity/Context';

export function mayCoalesce<T>(...args: Array<Optional<T>>): T | undefined {
for (const a of args) {
if (doesExist(a)) {
return a;
}
}

return undefined;
}

export function redirectContext(original: Context, redirect: ContextRedirect): Context {
const channel = mustCoalesce(redirect.forces.channel, original.channel, redirect.defaults.channel);
const target = mustCoalesce(redirect.forces.target, original.target, redirect.defaults.target);
const target = mayCoalesce(redirect.forces.target, original.target, redirect.defaults.target);
const loopTarget = defaultWhen(redirect.forces.loopback === true, original.source, target);

const user = original.user;
Expand Down
11 changes: 3 additions & 8 deletions test/controller/TestAccountController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { Context } from '../../src/entity/Context';
import { Locale } from '../../src/locale';
import { Schema } from '../../src/schema';
import { createService, createServiceContainer } from '../helpers/container';
import { getTestContextData } from '../helpers/context';

const TEST_DATA = {
filters: [],
Expand Down Expand Up @@ -60,11 +61,8 @@ describe('account controller', async () => {
await ctrl.getGrant(ineeda<Command>({
get: () => tvals,
}), ineeda<Context>({
...getTestContextData(),
checkGrants,
sourceUser: {
name: 'test',
uid: 'test',
},
}));

expect(checkGrants).to.have.callCount(tvals.length);
Expand Down Expand Up @@ -125,10 +123,7 @@ describe('account controller', async () => {
});

const context = ineeda<Context>({
sourceUser: {
name: 'test',
uid: 'test',
},
...getTestContextData(),
user: {
locale: {
lang: 'test',
Expand Down
2 changes: 2 additions & 0 deletions test/controller/TestWeatherController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { TransformModule } from '../../src/module/TransformModule';
import { Transform } from '../../src/transform';
import { RequestFactory } from '../../src/utils/Request';
import { createService, createServiceContainer } from '../helpers/container';
import { getTestContextData } from '../helpers/context';

describe('weather controller', async () => {
it('should send a message', async () => {
Expand Down Expand Up @@ -76,6 +77,7 @@ describe('weather controller', async () => {

const cmd = new Command({
context: ineeda<Context>({
...getTestContextData(),
checkGrants: () => true,
getGrants: () => ['*:test'],
user: ineeda<User>(),
Expand Down
11 changes: 5 additions & 6 deletions test/controller/github/TestApproveController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,12 @@ import { GithubApproveController } from '../../../src/controller/github/ApproveC
import { STATUS_SUCCESS } from '../../../src/endpoint/BaseEndpoint';
import { Command, CommandVerb } from '../../../src/entity/Command';
import { Context } from '../../../src/entity/Context';
import { Transform } from '../../../src/transform';
import { GithubClient } from '../../../src/utils/github';
import { createService, createServiceContainer } from '../../helpers/container';
import { getTestContextData } from '../../helpers/context';

/* eslint-disable @typescript-eslint/naming-convention,@typescript-eslint/no-explicit-any, camelcase */

const TEST_TRANSFORM = 'test-transform';
const TEST_DATA = {
client: {
agent: '',
Expand Down Expand Up @@ -70,7 +69,7 @@ function pullGetResponse(pulls: Array<unknown>): ClientResponse<Octokit.PullsGet
sha: '',
},
user: {
login: '',
login: 'test',
},
} as any,
headers: {} as any,
Expand Down Expand Up @@ -164,7 +163,7 @@ describe('github approve controller', async () => {
labels: {},
noun: '',
verb: CommandVerb.Create,
}), ineeda<Context>());
}), new Context(getTestContextData()));

expect(sendMessage).to.have.callCount(1);
expect(sendMessage).to.have.been.calledWithMatch({
Expand Down Expand Up @@ -210,7 +209,7 @@ describe('github approve controller', async () => {
labels: {},
noun: '',
verb: CommandVerb.Create,
}), ineeda<Context>());
}), new Context(getTestContextData()));

expect(sendMessage).to.have.callCount(1);
expect(sendMessage).to.have.been.calledWithMatch({
Expand Down Expand Up @@ -392,7 +391,7 @@ describe('github approve controller', async () => {
labels: {},
noun: '',
verb: CommandVerb.Create,
}), ineeda<Context>());
}), new Context(getTestContextData()));

expect(sendMessage).to.have.callCount(pulls.length);
});
Expand Down
Loading

0 comments on commit 88b0c85

Please sign in to comment.