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(server): add a subscriptions server #1397

Merged
merged 4 commits into from
Sep 6, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
48 changes: 48 additions & 0 deletions src/runtime/server/server.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import chalk from 'chalk'
import createExpress, { Express } from 'express'
import { GraphQLError, GraphQLSchema } from 'graphql'
import * as HTTP from 'http'
import { HttpError } from 'http-errors'
import { isEmpty } from 'lodash'
import * as Net from 'net'
import * as Plugin from '../../lib/plugin'
import { httpClose, httpListen, noop } from '../../lib/utils'
Expand Down Expand Up @@ -106,9 +108,47 @@ export function create(appState: AppState) {
loadedRuntimePlugins
)

/**
* Resolve if subscriptions are enabled or not
*/

let enableSubscriptionsServer: boolean = false
Copy link
Member Author

Choose a reason for hiding this comment

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

The following comment is really reflection on the Setset library.

It would be great if Setset could have initializers that depend upon external data.

This would require initializers to not run at construction time but at "assembly" time. External data would be passed at this time. And initializers would then run.

This would mean it would not be possible for users to access settings data and metadata before assembly. At least those that depend on assembly.

We could call these settings "assembled settings".

Maybe assembled settings would have a special initialized state before assembly. Like a constant "__PENDING_ASSEMBLY__". That could work from a runtime point of view.

What about from a static point of view? Firstly, like Setset.Leaf we would need a new type Setset.Assembled.

Then we would need the new .assemble method to return a statically transformed version of the settings wherein "__PENDING_ASSEMBLY__" would be stripped as a type.

Example:

// foo is an assembled setting

settings.data.foo // number | "__PENDING_ASSEMBLY__"
settings = settings.assemble()
settings.data.foo // number

This static behaviour looks NTH at best for Nexus b/c end users wouldn't be seeing this static transformation b/c it happens internally within Nexus.

What would be user facing though is this case:

settings.data.foo // number | "__PENDING_ASSEMBLY__"
settings.change({ foo: 1 })
settings.data.foo // should be: number
                  // actual:    number | "__PENDING_ASSEMBLY__"

Assembled initializers don't matter once the user has explicitly set the setting.

Like before we could capture the transformation in the return value of .change() (maybe...) however the mutative quality of Setset is currently an important DX aspect of it so it can be used as an e.g. singleton. ... This looks like an impossible problem to solve not withstanding new features from TS itself.

Typegen doesn't help because the effect lives between LOC.

One solution could be a utility to strip the pending assembly type:

settings.data.foo // number | "__PENDING_ASSEMBLY__"
settings.change({ foo: 1 })
Setset.notPendingAssembly(settings.data.foo) // number

Statically this would strip the "__PENDING_ASSEMBLY__" type. Dynamically it would check that the value isn't "__PENDING_ASSEMBLY__". Those dynamic checks could be disabled in production.

If most settings were assembled and the user often accessed those settings having to wield this utility function often could get very annoying.

But frankly it is totally unclear if that is the case. For example in Nexus the number of users that are going to be checking the settings.data.server.subscriptions.enabled option seems to be near zero.

So overall my conclusion is:

  • introducing the concept of assembly removes buggy code from the system
    • internally more related logic gets to be colocated
    • extenerally users won't see the simply wrong settings.data.server.subscriptions.enabled // false when its actually true because they defined subscription type in this schema
  • the static type of pending assembly allows for the effect of assembly to be tracked for users
  • it is not possible to track .change effects mutatively so the utility function notPendingAssembly can come to the rescue in rare (?) occasions when user needs to deal with the assembled setting explicitly


if (settings.metadata.fields.subscriptions.fields.enabled.from === 'change') {
enableSubscriptionsServer = settings.data.subscriptions.enabled
/**
* Validate the integration of server subscription settings and the schema subscription type definitions.
*/
if (hasSubscriptionFields(schema)) {
if (!settings.data.subscriptions.enabled) {
log.error(
`You have disabled server subscriptions but your schema has a ${chalk.yellowBright(
'Subscription'
)} type with fields present. When your API clients send subscription operations at runtime they will fail.`
)
}
} else if (settings.data.subscriptions.enabled) {
log.warn(
`You have enabled server subscriptions but your schema has no ${chalk.yellowBright(
'Subscription'
)} type with fields.`
)
}
} else if (hasSubscriptionFields(schema)) {
enableSubscriptionsServer = true
}

/**
* Setup Apollo Server
*/

state.apolloServer = new ApolloServerExpress({
schema,
engine: settings.data.apollo.engine.enabled ? settings.data.apollo.engine : false,
// todo expose options
// subscriptions: {
// // keepAlive:
// },
context: createContext,
introspection: settings.data.graphql.introspection,
formatError: errorFormatter,
Expand All @@ -127,6 +167,10 @@ export function create(appState: AppState) {
cors: settings.data.cors,
})

if (enableSubscriptionsServer) {
state.apolloServer.installSubscriptionHandlers(state.httpServer)
}

return { createContext }
},
async start() {
Expand Down Expand Up @@ -217,3 +261,7 @@ function createContextCreator(

return createContext
}

function hasSubscriptionFields(schema: GraphQLSchema): boolean {
return !isEmpty(schema.getSubscriptionType()?.getFields())
}
19 changes: 19 additions & 0 deletions src/runtime/server/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ export type PlaygroundLonghandInput = {
}

export type SettingsInput = {
subscriptions?:
| boolean
| {
enabled?: boolean
}
/**
* Port the server should be listening on.
*
Expand Down Expand Up @@ -212,6 +217,20 @@ export type SettingsData = Setset.InferDataFromInput<Omit<SettingsInput, 'host'
export const createServerSettingsManager = () =>
Setset.create<SettingsInput, SettingsData>({
fields: {
subscriptions: {
shorthand(enabled) {
return { enabled }
},
fields: {
enabled: {
initial() {
// This is not accurate. The default is actually dynamic depending
// on if the user has defined any subscription type or not.
return true
Copy link
Member Author

Choose a reason for hiding this comment

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

See large design comment about Setset

},
},
},
},
apollo: {
fields: {
engine: {
Expand Down