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

Starting dev server for first time throws 408 timeouts on initial fetch to populate readable store - restart dev server and it goes away #1644

Closed
nstuyvesant opened this issue Jun 6, 2021 · 8 comments

Comments

@nstuyvesant
Copy link
Contributor

nstuyvesant commented Jun 6, 2021

Environment
SvelteKit v1.0.0-next.144
Svelte 3.42.1
OS: macOS 11.5.1
Browser: Safari 14.1.2 and Chrome 92

Describe the bug
If I bump any dependencies then run npm install && npm run dev -- --open, I get HTTP 408 errors when my readable stores are created via GETs to my API (same project - not external). If I immediately do a Ctrl-C and restart the dev server, the errors go away.

Logs (showing the errors then the errors going away after restarting dev server)

% npm run dev -- --open

shy-svelte@3.0.0.alpha-1 dev
svelte-kit dev "--open"

SvelteKit v1.0.0-next.144

local: http://localhost:3000
network: not exposed

Use --host to expose server to other devices on this network

12:08:27 PM [vite] new dependencies found: sveltestrap/src, updating...
Getting readable store: /api/location/active.json
12:08:28 PM [vite] ✨ dependencies updated, reloading page...
First request throws a 408 here

{
  size: 0,
  [Symbol(Body internals)]: {
    body: PassThrough {
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 5,
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: true,
      [Symbol(kCapture)]: false,
      [Symbol(kCallback)]: null
    },
    boundary: null,
    disturbed: false,
    error: null
  },
  [Symbol(Response internals)]: {
    url: 'http://localhost:3000/api/product/active.json',
    status: 408,
    statusText: 'Request Timeout',
    headers: {
      'access-control-allow-origin': '*',
      connection: 'close',
      'content-length': '139',
      date: 'Fri, 25 Jun 2021 03:31:20 GMT'
    },
    counter: 0,
    highWaterMark: 16384
  }
}

Failed API call: Error: Bad response trying to retrieve from http://localhost:3000/api/location/active.json.
at getArray (/src/stores.ts:9:11)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
^C
nates@Nates-MacBook-Pro shy-svelte % npm run dev -- --open

shy-svelte@3.0.0.alpha-1 dev
svelte-kit dev "--open"

SvelteKit v1.0.0-next.144

local: http://localhost:3000
network: not exposed

Use --host to expose server to other devices on this network

Getting readable store: /api/location/active.json
12:09:29 PM [vite] new dependencies found: @fortawesome/free-brands-svg-icons, updating...
12:09:30 PM [vite] ✨ dependencies updated, reloading page...
Getting readable store: /api/location/active.json

// stores.ts
import { readable, Readable } from 'svelte/store'

const { VITE_WEB_URL } = import.meta.env

const getArray = async (url: string) => {
  const response: Response = await fetch(url)
  if (!response.ok) throw {
    console.error('First request throws a 408 here', response)
    new Error(`Bad response trying to retrieve from ${url}.`)
  }
  return await response.json()
}

const getReadableStore = (url: string) => readable([], set => {
  console.log(`Getting readable store: ${url}`)
  getArray(`${VITE_WEB_URL}${url}`)
    .then(set)
    .catch(err => console.error('Failed API call:', err))
  return () => {}
})

type SearchableStoreArrays = StudioLocation[] | []
type FindParentRecordResults = (arrayOfRecords: SearchableStoreArrays, id: number) => any
export const findParentRecord: FindParentRecordResults = (arrayOfRecords, id: number) => {
  const foundRecord = arrayOfRecords.find( ({ _id }) => _id === id )
  return foundRecord ? foundRecord : {}
}

export const locations = <Readable<StudioLocation[]>> getReadableStore('/api/location/active.json')

Here's the path it takes for the GET from /api/location/active.json...

// src/routes/api/location/active.json.ts
import type { RequestHandler } from '@sveltejs/kit'
import { getLocations } from './_location.controller'

// GET /api/location/active.json
export const get: RequestHandler = async () => {
  return await getLocations(true) // active only
}
// src/routes/api/location/_location.controller.ts
import { query } from '../_db'

type GetLocationsResponse = (activeOnly: boolean) => Promise<{ body: StudioLocation[] }>

export const getLocations: GetLocationsResponse = async (activeOnly: boolean) => {
  const sql = activeOnly ?
    `SELECT * FROM locations_active;`:
    `SELECT * FROM locations_all;`
  const { rows } = await query(sql)
  return {
    body: <StudioLocation[]> rows
  }
}
// /src/routes/api/_db.ts
import pg from 'pg'

const pgNativePool = new pg.native.Pool({
  max: 10,
  connectionString: import.meta.env.VITE_DATABASE_URL,
  ssl: {
    rejectUnauthorized: false
  }
});

type QueryResponse = (sql: string, params?: Array<number|string|boolean>) => Promise<pg.QueryResult<any>>
export const query: QueryResponse = (sql: string, params?: Array<number|string|boolean>) => pgNativePool.query(sql, params)

Severity
Severity is medium because I can always Ctrl-C and restart the dev server but it might create an impression of instability in SvelteKit which is why I didn't mark this as low.

Perhaps the initial fetch is failing because something is still being initialized by SvelteKit and the dev server isn't really up and running?

@nstuyvesant nstuyvesant changed the title Starting dev server for first time throws errors (second time and beyond - no errors) Starting dev server for first time throws timeouts on initial fetches to Jun 27, 2021
@nstuyvesant nstuyvesant changed the title Starting dev server for first time throws timeouts on initial fetches to Starting dev server for first time throws 408 timeouts on initial fetch to populate readable store - restart dev server and it goes away Jun 27, 2021
@frederikhors
Copy link
Contributor

Same here, Windows and Mac.

@manen
Copy link

manen commented Jul 21, 2021

Same here, Linux. Doesn't solve it even with a restart.

@nstuyvesant
Copy link
Contributor Author

Just installed SvelteKit v1.0.0-next.146 and the problem (so far) has not reoccured. I believe this change:

[fix] enable Vite pre-bundling except for Svelte packages (#2137)
is what cured this issue.

@frederikhors and @manen - can you please upgrade SvelteKit to v.1.0.0-next.146 and see if the problem goes away for you as well?

@frederikhors
Copy link
Contributor

Same here, Linux. Doesn't solve it even with a restart.

You need to restart many times!

@frederikhors
Copy link
Contributor

Just installed SvelteKit v1.0.0-next.146 and the problem (so far) has not reoccured. I believe this change:

[fix] enable Vite pre-bundling except for Svelte packages (#2137)
is what cured this issue.

@frederikhors and @manen - can you please upgrade SvelteKit to v.1.0.0-next.146 and see if the problem goes away for you as well?

Gimme some hours... and I will let you know!

@frederikhors
Copy link
Contributor

1.0.0-next.146 fixes the issue for me (Windows 10).

I think that now I will cry with happiness.

You can close this issue!

@manen
Copy link

manen commented Aug 10, 2021

I use the load function now, so for me it's solved. thanks though

@nstuyvesant
Copy link
Contributor Author

Solved by @sveltejs/kit@1.0.0-next.146.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants