sveltejs / kit

web development, streamlined
https://svelte.dev/docs/kit
MIT License
18.73k stars 1.94k forks source link

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 closed 3 years ago

nstuyvesant commented 3 years ago

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?

frederikhors commented 3 years ago

Same here, Windows and Mac.

manen commented 3 years ago

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

nstuyvesant commented 3 years ago

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 commented 3 years ago

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

You need to restart many times!

frederikhors commented 3 years ago

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 commented 3 years ago

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 commented 3 years ago

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

nstuyvesant commented 3 years ago

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